How to convert object array to string array in Java
Asked Answered
C

11

280

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 ?

Caryl answered 19/6, 2009 at 16:0 Comment(1)
I like waxwing's answer the best : String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class); It's very concise and works. I counted how much time it takes for both his answer and my current approach, they are pretty much the same.Caryl
D
413

Another alternative to System.arraycopy:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
Debase answered 19/6, 2009 at 16:11 Comment(5)
only on Java 1.6 and aboveScarecrow
Hrm. I couldn't get this one to work, where the long-form example in the original question does work. It throws java.lang.ArrayStoreException. I'm getting the object array from the toArray method on a generic ArrayList containing my custom type. Is this not expected to work with generics or something?Hensley
@Ian, the issue is that objectArray contains Objects not Strings (see mmyers comment to my answer which suffers from the same problem).Yellow
I just tried this approach and, at least in my case, I found out that performance is not as good as building the array myself by iterating. (Too bad though, I liked it as a one-liner!)Trilogy
@Trilogy - pretty long one liner. wrap it in a method perhaps.Decolorize
T
109

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);
Tartuffe answered 20/4, 2014 at 1:46 Comment(3)
This is a work of beauty and satisfies the requirement of being able to aesthetically convert a non-String object array to an array of their toString equivalents. The currently accepted answer does not accomplish this.Pee
This works but if your list contains nulls you'll get a NullPointerException. To get around that issue see: #4581907Beatriz
I get an Android Studio IDE error when using Arrays.stream. "Cannot resolve method 'stream()'. I know I am on the correct version of Java.Ringed
Y
67

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

 Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);
Yellow answered 19/6, 2009 at 16:8 Comment(4)
That only works if the objects are all Strings; his current code works even if they are not.Towns
Good point. I understood the toString as just being a way of casting to a String, not the intention of actually replacing the objects with something else. If that is what you need to do, then looping is the only way.Yellow
this does not work in Android 2.3.3.. it gives me an error saying that copyof method is not defined. I imported all the right files (ctrl+shift+I).. but it still does not work.Cadwell
@user590849, my answer doesn't use copyof. Are you refering to another answer?Yellow
W
51

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.

Wanitawanneeickel answered 30/11, 2012 at 14:25 Comment(3)
Slight correction performance wise: String tArray[] = tList.toArray(new String[tList.size()]); Otherwise the array has to be resized again...Eris
Good explanation. Just one more thing, if memory consumption or performance is an issue, do not duplicate the array. Either cast an element in String whenever you need it (String)Object_Array[i] or Object_Array[i].toString() or allocate the array as a String array Object Object_Array[]=new String[100]; ... get values ... then cast String_Array=(String[])Object_Array which now works.Charlinecharlock
this throws ArrayStoreExceptionCigarette
G
7

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.

Gullet answered 19/6, 2009 at 16:8 Comment(2)
@Yishai: no, arrays do not implement Iterable. iteration over them is specially defined in the JLSScarecrow
@newacct, quite true, I meant arrays can be easily wrapped in an Iterable (Arrays.asList()). I don't know why it came out that way.Yellow
O
7

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.

Oquassa answered 19/6, 2009 at 16:14 Comment(3)
Interesting suggestion, but you'd first have to remove the [ and ] on the first and last elements.Towns
gorgeous until it performs the job :)Vday
This doesn't work if any String contains a comma (,)Alert
P
5

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;
Plainsman answered 19/6, 2009 at 16:11 Comment(0)
S
4

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);
Semiotics answered 23/5, 2015 at 15:29 Comment(0)
N
3

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.

Nyssa answered 24/11, 2011 at 0:5 Comment(0)
I
2
Object arr3[]=list1.toArray();
   String common[]=new String[arr3.length];

   for (int i=0;i<arr3.length;i++) 
   {
   common[i]=(String)arr3[i];
  }
Intolerant answered 7/1, 2015 at 6:53 Comment(0)
A
1

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]); 
        }
Aeromechanics answered 10/12, 2013 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.