David Parks
David Parks

Reputation: 32111

Converting an array of one type to an array of a subtype

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;
}

Upvotes: 4

Views: 4399

Answers (4)

shazin
shazin

Reputation: 21923

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);
}

Upvotes: 0

Vivek
Vivek

Reputation: 1336

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[].

Upvotes: 0

oshai
oshai

Reputation: 15375

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

Upvotes: 0

threenplusone
threenplusone

Reputation: 2122

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.

Upvotes: 10

Related Questions