views:

9453

answers:

6

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 ?

+3  A: 

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.

Brian Agnew
Actually, a String[] *is* an Object[]. Did you mean the other way around (that an Object[] is not a String[])?
newacct
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
@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
+4  A: 

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
That only works if the objects are all Strings; his current code works even if they are not.
Michael Myers
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
+2  A: 

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
Arrays implement Iterable.
Yishai
@Yishai: no, arrays do not implement Iterable. iteration over them is specially defined in the JLS
newacct
@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
+7  A: 

Another alternative to System.arraycopy:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
waxwing
only on Java 1.6 and above
newacct
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
@Ian, the issue is that objectArray contains Objects not Strings (see mmyers comment to my answer which suffers from the same problem).
Yishai
+1  A: 

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.
+2  A: 

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
Interesting suggestion, but you'd first have to remove the [ and ] on the first and last elements.
Michael Myers
ok, you are right, I forgot about them
Ilya Boyandin
gorgeous until it performs the job :)
Aizaz