Hi, everyone,
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.
Hi, everyone,
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.
this is conversion
for(int i = 0 ; i < objectArr.length ; i ++){
try{
strArr[i] = objectArr[i].toString();
}catch(NullPointerException ex){
// do some default initilization
}
}
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
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];
}
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);
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.