How to Convert Object Array to String Array in Java

How to convert object array to string array in Java

Another alternative to System.arraycopy:

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

Converting object array to string array

Override the toString() methods on the objects so that each type returns properly-formatted strings.

Or, if you want to maintain the original toString() method intact, create a new interface that is shared by all the object types you want to print, and that provides the same "shared method" through all those objects, with each object type specifying the interface's method's behavior.

Convert List Object to String[] in Java

You have to loop through the list and fill your String[].

String[] array = new String[lst.size()];
int index = 0;
for (Object value : lst) {
array[index] = (String) value;
index++;
}

If the list would be of String values, List then this would be as simple as calling lst.toArray(new String[0]);

Convert any array of any type into string

Write a utility method like below:

public static String convertToString(Object input){
if (input instanceof Object[]) {
// deepToString used to handle nested arrays.
return Arrays.deepToString((Object[]) input);
} else {
return input.toString();
}
}

Please note that the first if condition would be evaluated to false if the input is a primitive array like int[], boolean[], etc. But it would work for Integer[] etc.
If you want the method to work for primitive arrays, then you need to add conditions for each type separately like:

else if (input instanceof int[]){
// primitive arrays cannot be nested.
// hence Arrays.deepToString is not required.
return Arrays.toString((Object[]) input);
}


Related Topics



Leave a reply



Submit