277

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 ?

Kristian Glass
  • 37,325
  • 7
  • 45
  • 73
Frank
  • 30,590
  • 58
  • 161
  • 244
  • 3
    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. – Frank Jun 19 '09 at 18:00

11 Answers11

408

Another alternative to System.arraycopy:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
waxwing
  • 18,547
  • 8
  • 66
  • 82
  • 61
    only on Java 1.6 and above – newacct Jul 05 '09 at 09:53
  • 11
    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? – Ian Varley Feb 07 '10 at 19:41
  • 4
    @Ian, the issue is that objectArray contains Objects not Strings (see mmyers comment to my answer which suffers from the same problem). – Yishai Jul 02 '10 at 15:40
  • 3
    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!) – mdup Jun 12 '13 at 15:48
  • 1
    @mdup - pretty long one liner. wrap it in a method perhaps. – MasterJoe Sep 04 '16 at 18:49
105

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);
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
  • 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. – b4n4n4p4nd4 Jan 11 '18 at 21:34
  • 2
    This works but if your list contains nulls you'll get a NullPointerException. To get around that issue see: https://stackoverflow.com/questions/4581407/how-can-i-convert-arraylistobject-to-arrayliststring – Tony Falabella Apr 29 '19 at 18:24
  • 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. – GhostRavenstorm Sep 30 '21 at 21:05
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]);
Yishai
  • 90,445
  • 31
  • 189
  • 263
  • 10
    That only works if the objects are all Strings; his current code works even if they are not. – Michael Myers Jun 19 '09 at 16:12
  • 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. – Yishai Jun 19 '09 at 16:14
  • 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. – user590849 Oct 26 '12 at 22:31
  • 3
    @user590849, my answer doesn't use `copyof`. Are you refering to another answer? – Yishai Oct 28 '12 at 02:34
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.

Capagris
  • 3,314
  • 1
  • 15
  • 10
  • Slight correction performance wise: String tArray[] = tList.toArray(new String[tList.size()]); Otherwise the array has to be resized again... – Lonzak Dec 18 '14 at 20:44
  • 1
    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. – Solostaran14 Mar 24 '15 at 17:26
  • 1
    this throws ArrayStoreException – iltaf khalid Feb 25 '17 at 12:33
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.

Richard
  • 9,972
  • 4
  • 26
  • 32
  • 1
    @Yishai: no, arrays do not implement Iterable. iteration over them is specially defined in the JLS – newacct Jun 21 '09 at 18:46
  • @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. – Yishai Jul 02 '10 at 16:59
6

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.

Ilya Boyandin
  • 3,069
  • 25
  • 23
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;
david a.
  • 5,283
  • 22
  • 24
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);
lstypka
  • 41
  • 1
  • 2
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.

animuson
  • 53,861
  • 28
  • 137
  • 147
ttt
  • 3,934
  • 8
  • 46
  • 85
2
Object arr3[]=list1.toArray();
   String common[]=new String[arr3.length];

   for (int i=0;i<arr3.length;i++) 
   {
   common[i]=(String)arr3[i];
  }
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]); 
        }