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
Parsing a String to Date Format in Java Defaults Date to 1 and Month to January
MAC Os X and Multiple Java Versions
Covariance, Invariance and Contravariance Explained in Plain English
Different Between Parseint() and Valueof() in Java
Generic Type Inference Not Working with Method Chaining
Painting the Slider Icon of Jslider
How to Derive Module Descriptor: Provider {Class X} Not in Module
How Are Integers Internally Represented at a Bit Level in Java
How to Synchronize a Static Variable Among Threads Running Different Instances of a Class in Java
Java Compiled Classes Contain Dollar Signs
How to Add Native Library to "Java.Library.Path" with Eclipse Launch (Instead of Overriding It)
Java Split() Method Strips Empty Strings at the End
How to Create a Zip File in Java
How to Convert a Java 8 Intstream to a List
Gradle Does Not Find Tools.Jar