开发者

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

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


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

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

Tweak2

 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


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

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);


Java 8 solution:

String[] strArr = Arrays.stream(objArr).map(Object::toString).toArray(String[]::new);


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

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


I guess you could also use System.arraycopy

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

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


My point is not fit for the answer exactly (scenario specific), but it may happen someone unknowingly ended upon in object[].

in my case I was trying to convert List to String[] & on using .toArray() on list, it converted it to Object[]

So, specific to the mentioned scenario, a one-line solution

List<String> list = Arrays.asList("a", "b", "c", "d");
String[] array = list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(array)); // [a, b, c, d]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜