4

我想将数组从一种类型转换为另一种类型。如下所示,我遍历第一个数组中的所有对象并将它们转换为第二个数组类型。

但这是最好的方法吗?有没有一种不需要循环和投射每个项目的方法?

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

4 回答 4

10

你应该能够使用这样的东西:

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

然而,这可能只是在引擎盖下循环和投射。

这里

于 2012-11-15T04:52:32.427 回答
0

如果可能的话,我建议与List而不是一起工作Array

于 2012-11-15T04:55:42.140 回答
0

这是如何做到的:

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

请记住,您不能反过来做,即您不能将 Employee[] 转换为 TechEmployee[]。

于 2012-11-15T05:03:01.827 回答
0

如果你喜欢,这样的事情是可能的

public MySubtype[] convertType(MyObject[] myObjectArray){
   MySubtype[] subtypeArray = new MySubtype[myObjectArray.length];
   List<MyObject> subs = Arrays.asList(myObjectArray);   
   return subs.toArray(subtypeArray);
}
于 2012-11-15T05:03:07.603 回答