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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With