up vote 37 down vote favorite
13
share [g+] share [fb]

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 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 ?

link|improve this question

78% accept rate
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
feedback

8 Answers

up vote 43 down vote accepted

Another alternative to System.arraycopy:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
link|improve this answer
8  
only on Java 1.6 and above – newacct Jul 5 '09 at 9:53
1  
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 7 '10 at 19:41
@Ian, the issue is that objectArray contains Objects not Strings (see mmyers comment to my answer which suffers from the same problem). – Yishai Jul 2 '10 at 15:40
feedback

A String[] is not an Object[], which is a little counter-intuitive. You're encountering the "Banana is-a fruit" but a "List Of Bananas is-not-a List Of Fruit" scenario.

You will have to extract and rebuild, as you're currently doing.

link|improve this answer
Actually, a String[] is an Object[]. Did you mean the other way around (that an Object[] is not a String[])? – newacct Jun 19 '09 at 17:26
1  
No. If String[] were Object[] then you could define a function that took an Object[], pass it a String[] and then place a Integer in the array, violating type safety. An array of Foo is never an array of Bar even if Bar is a kind of Foo – Jherico Jun 20 '09 at 1:24
2  
@Jherico: Yes, and you could define such a function (try it if you don't believe me). It would throw an ArrayStoreException at runtime though. – newacct Jun 20 '09 at 4:18
feedback

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

 Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);
link|improve this answer
1  
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
feedback

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.

link|improve this answer
Arrays implement Iterable. – Yishai Jun 19 '09 at 16:15
@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 2 '10 at 16:59
feedback

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;
link|improve this answer
feedback

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.

link|improve this answer
1  
Interesting suggestion, but you'd first have to remove the [ and ] on the first and last elements. – Michael Myers Jun 19 '09 at 16:15
ok, you are right, I forgot about them – Ilya Boyandin Jun 19 '09 at 16:20
gorgeous until it performs the job :) – Algo Oct 27 '10 at 12:14
feedback

Following code throws exception regarding casting. I also tried to create two arrays and cast each item of array separately but I also get exception. I'm using JDK 6.

// Reload the data into a local auxiliary variable (myArray)
  int[] myArray = (int[])evt.getNewValue();

What's the right solution to cast from Object to Integer when Object stores byte primitives.

Regards

link|improve this answer
You should ask this as a new question, not as an answer to another question. – Christian Semrau Mar 12 '11 at 15:42
feedback

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.