Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

oop

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;
}
like image 598
David Parks Avatar asked Dec 27 '22 14:12

David Parks


1 Answers

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.

like image 165
threenplusone Avatar answered Dec 29 '22 03:12

threenplusone