4

I want to convert an array from one type to another. As shown below, I loop over all objects in the first array and cast them to the 2nd array type.

But is this the best way to do it? Is there a way that doesn't require looping and casting each item?

public MySubtype[] convertType(MyObject[] myObjectArray){
   MySubtype[] subtypeArray = new MySubtype[myObjectArray.length];

   for(int x=0; x < myObjectArray.length; x++){
      subtypeArray[x] = (MySubtype)myObjectArray[x];
   }

   return subtypeArray;
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
David Parks
  • 30,789
  • 47
  • 185
  • 328
  • An API provides me an array of Writables (akin to Object in this context). It's Hadoop and ArrayWritable, which is used for specialized serialization of arrays. I need to cast the base type returned from ArrayWritable (I don't control) back to its original type. The reason all of this is an issue for ArrayWritable is a combination of type erasure and efficiency demands at large scale under certain circumstances. – David Parks Nov 15 '12 at 05:39

4 Answers4

10

You should be able to use something like this:

Arrays.copyOf(myObjectArray, myObjectArray.length, MySubtype[].class);

However this may just be looping and casting under the hood anyway.

See here.

Community
  • 1
  • 1
threenplusone
  • 2,112
  • 19
  • 28
0

I would suggest working with List instead of Array if possible.

oshai
  • 14,865
  • 26
  • 84
  • 140
0

Here is how to do it:

public class MainTest {

class Employee {
    private int id;
    public Employee(int id) {
        super();
        this.id = id;
    }
}

class TechEmployee extends Employee{

    public TechEmployee(int id) {
        super(id);
    }

}

public static void main(String[] args) {
    MainTest test = new MainTest();
    test.runTest();
}

private void runTest(){
    TechEmployee[] temps = new TechEmployee[3];
    temps[0] = new TechEmployee(0);
    temps[1] = new TechEmployee(1);
    temps[2] = new TechEmployee(2);
    Employee[] emps = Arrays.copyOf(temps, temps.length, Employee[].class);
    System.out.println(Arrays.toString(emps));
}
}

Just remember you cannot do it the other way around, i.e. you cannot convert Employee[] to a TechEmployee[].

Vivek
  • 1,316
  • 1
  • 13
  • 23
0

Something like this is possible if you fancy

public MySubtype[] convertType(MyObject[] myObjectArray){
   MySubtype[] subtypeArray = new MySubtype[myObjectArray.length];
   List<MyObject> subs = Arrays.asList(myObjectArray);   
   return subs.toArray(subtypeArray);
}
shazin
  • 21,379
  • 3
  • 54
  • 71