How to convert object array to string array in Java

JavaArraysString

Java Problem Overview


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 ?

Java Solutions


Solution 1 - Java

Another alternative to System.arraycopy:

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

Solution 2 - Java

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);

Solution 3 - Java

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

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

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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.

Solution 7 - Java

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;

Solution 8 - Java

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);

Solution 9 - Java

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.

Solution 10 - Java

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

Solution 11 - Java

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]);	
		}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrankView Question on Stackoverflow
Solution 1 - JavawaxwingView Answer on Stackoverflow
Solution 2 - JavaVitalii FedorenkoView Answer on Stackoverflow
Solution 3 - JavaYishaiView Answer on Stackoverflow
Solution 4 - JavaCapagrisView Answer on Stackoverflow
Solution 5 - JavaRichardView Answer on Stackoverflow
Solution 6 - JavaIlya BoyandinView Answer on Stackoverflow
Solution 7 - Javadavid a.View Answer on Stackoverflow
Solution 8 - JavalstypkaView Answer on Stackoverflow
Solution 9 - JavatttView Answer on Stackoverflow
Solution 10 - JavaAmit Kumar SagarView Answer on Stackoverflow
Solution 11 - JavaRahul ChhanganiView Answer on Stackoverflow