Convert an array of one type to an array of subtype

I want to convert an array from one type to another. As shown below, I iterate over all the objects in the first array and pass them to the second type of array.

But is this the best way to do this? Is there a way that does not require a cycle and casting of each element?

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; } 
+4
source share
4 answers

You should be able to use something like this:

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

However, it can just be looping and casting under the hood.

See here .

+8
source

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

0
source

Here's 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 that you cannot do it the other way around i.e. you cannot convert Employee [] to TechEmployee [].

0
source

Something like this is possible if you want

 public MySubtype[] convertType(MyObject[] myObjectArray){ MySubtype[] subtypeArray = new MySubtype[myObjectArray.length]; List<MyObject> subs = Arrays.asList(myObjectArray); return subs.toArray(subtypeArray); } 
0
source

Source: https://habr.com/ru/post/1446136/


All Articles