How to convert the Object[] to String[] in Java?
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 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];
}
Java 8 solution:
String[] strArr = Arrays.stream(objArr).map(Object::toString).toArray(String[]::new);
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