1

How can I expand an array without knowing its type?

I have an Object[], and I know it contains only, say, Car instances. When I try to typecast it to a Car[], it throws a ClassCastException. I'm working in an environment where Generics are not available.

Must I use a for-loop to copy each element manually into a new array like this:

Car[] cars = new Car[objects.length];
for (int i = 0; i < objects.length; i++) {
    cars[i] = (Car) objects[i];
}

?

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • 1
    possible duplicate of [How to convert object array to string array in Java](http://stackoverflow.com/questions/1018750/how-to-convert-object-array-to-string-array-in-java) - Yes, that's with `String[]`, but it's the same thing / reason / answer. – Brian Roach Oct 30 '11 at 16:54
  • Hmm, don't think its a duplicate, as this is more about the runtime type of an arbitrary array. – JimmyB Oct 30 '11 at 18:41

3 Answers3

5

Just because the Object[] happens only to contain Cars, doesn't mean it can be cast to Car[]. You would need to copy the contents of the array to a new Car[], casting where necessary.

Remember that arrays are themselves objects, and their type isn't governed by what's in them - it's the other way around.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
0

One issue you can run into is if the array has primitives, then you cannot cast it to Object[].

You can make this work with both primitives and Objects by using some helpers on java.lang.reflect.Array.

This is an example of how to process an array safely and convert all the values to String.

public String[] stringifyValue(Object value) {
        String[] arrayValue;

 
        if (value.getClass().isArray() ){
            int arrayLength = Array.getLength(value);
            arrayValue = new String[arrayLength];

            for (int i=0; i < arrayLength; i++) {
                arrayValue[i] = String.valueOf(Array.get(value, i));
            }
        }
    }
Jon
  • 3,212
  • 32
  • 35
0

In Java 6, you can use copyOf() to "resize" an array.

I don't now your actual problem, but a common solution to resize an array of arbitrary type in Java < 6 is:

Class elementType = oldArray.getClass().getComponentType();
Object[] newArray = (Object[])java.lang.reflect.Array.newInstance(elementType, newSize);

then you can use System.arraycopy() to copy values from the old array to the new one as needed.

JimmyB
  • 12,101
  • 2
  • 28
  • 44
  • I think the OP wants to change the type of the array, rather than just resize it - the question made it confusing by using the word "expand". Since the component type is known at compile time, reflection would be overkill anyway. – Paul Bellora Nov 01 '11 at 15:40
  • That may be true. And in that case, reflection is really not needed. – JimmyB Nov 01 '11 at 18:27