[java] How to convert object array to string array in Java

I use the following code to convert an Object array to a String array :

Object Object_Array[]=new Object[100];
// ... get values in the Object_Array

String String_Array[]=new String[Object_Array.length];

for (int i=0;i<String_Array.length;i++) String_Array[i]=Object_Array[i].toString();

But I wonder if there is another way to do this, something like :

String_Array=(String[])Object_Array;

But this would cause a runtime error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

What's the correct way to do it ?

This question is related to java arrays string

The answer is


I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.

First, let's see what Oracle has to say

 * <p>The returned array will be "safe" in that no references to it are
 * maintained by this list.  (In other words, this method must
 * allocate a new array even if this list is backed by an array).
 * The caller is thus free to modify the returned array.

It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?

List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();   

Probably, many of you would think that this code is doing the same, but it does not.

Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;

When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!

Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;   

So tList.toArray is instantiating a Objects and not Strings...

Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following

String tArray[] = tList.toArray(new String[0]);

Hope it is clear enough.


You can use type-converter. To convert an array of any types to array of strings you can register your own converter:

 TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {

        @Override
        public String[] convert(Object[] source) {
            String[] strings = new String[source.length];
            for(int i = 0; i < source.length ; i++) {
                strings[i] = source[i].toString();
            }
            return strings;
        }
    });

and use it

   Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
   String[] strings = TypeConverter.convert(objects, String[].class);

The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:

Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
        String apply(Object from){
             return from.toString();
        }
 });

This take you away from using arrays,but I think this would be my prefered way.


System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:

 Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);

Object arr3[]=list1.toArray();
   String common[]=new String[arr3.length];

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

For your idea, actually you are approaching the success, but if you do like this should be fine:

for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];

BTW, using the Arrays utility method is quite good and make the code elegant.


Easily change without any headche Convert any object array to string array Object drivex[] = {1,2};

    for(int i=0; i<drive.length ; i++)
        {
            Str[i]= drivex[i].toString();
            System.out.println(Str[i]); 
        }

If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.

If you know your Object array contains Strings only, you may also do (instread of calling toString()):

for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];

The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:

    Object[] o = new String[10];
    String[] s = (String[]) o;

In Java 8:

String[] strings = Arrays.stream(objects).toArray(String[]::new);

To convert an array of other types:

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

This one is nice, but doesn't work as mmyers noticed, because of the square brackets:

Arrays.toString(objectArray).split(",")

This one is ugly but works:

Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")

If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript