如何在 Java 中将 Object[] 转换为 String[]?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3880274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:49:15  来源:igfitidea点击:

How to convert the Object[] to String[] in Java?

javastringobject

提问by Questions

I have a question about Java. I have an Object[](Java default, not the user-defined) and I want to convert it to a String[]. Can anyone help me? thank you.

我有一个关于 Java 的问题。我有一个Object[](Java 默认的,不是用户定义的),我想将它转换为String[]. 谁能帮我?谢谢。

回答by Jigar Joshi

this is conversion

这是转换

for(int i = 0 ; i < objectArr.length ; i ++){  
   try {
      strArr[i] = objectArr[i].toString();
   } catch (NullPointerException ex) {
       // do some default initialization
   }
}  

This is casting

这是铸造

String [] strArr = (String[]) objectArr;  //this will give you class cast exception

Update:

更新:

Tweak 1

调整 1

 String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

Tweak2

调整2

 Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);

Note:That only works if the objects are all Strings; his current code works even if they are not

注意:只有当对象都是字符串时才有效;他当前的代码有效,即使它们不是

forTweak1 :only on Java 1.6 and above

forTweak1 :仅适用于 Java 1.6 及更高版本

回答by aioobe

Simply casting like this String[] strings = (String[]) objectArray;probably won't work.

像这样简单地投射String[] strings = (String[]) objectArray;可能行不通。

Try something like this:

尝试这样的事情:

public static String[] asStrings(Object... objArray) {
    String[] strArray = new String[objArray.length];
    for (int i = 0; i < objArray.length; i++)
        strArray[i] = String.valueOf(objArray[i]);
    return strArray;
}

You could then use the function either like this

然后您可以像这样使用该功能

Object[] objs = { "hello world", -1.0, 5 };
String[] strings = asStrings(objs);

or like this

或者像这样

String[] strings = asStrings("hello world", -1.0, 5);

回答by bdhar

I guess you could also use System.arraycopy

我想你也可以使用System.arraycopy

System.arraycopy(objarray, 0, strarray, 0, objarray.length);

provided, strarrayis of the length objarray.lengthand objarray contain only strings. Or it would throw ArrayStoreException. See aioobe's comment.

提供strarray的长度objarray.length和 objarray 只包含字符串。否则它会抛出 ArrayStoreException。请参阅 aioobe 的评论。

回答by nanda

I think this is the simplest way if all entries in objectArr are String:

如果 objectArr 中的所有条目都是字符串,我认为这是最简单的方法:

for(int i = 0 ; i < objectArr.length ; i ++){
    strArr[i] = (String) objectArr[i];
}