我想将数组从一种类型转换为另一种类型。如下所示,我遍历第一个数组中的所有对象并将它们转换为第二个数组类型。
但这是最好的方法吗?有没有一种方法不需要循环和转换每个项目?
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;
}
答案 0 :(得分:8)
你应该能够使用这样的东西:
Arrays.copyOf(myObjectArray, myObjectArray.length, MySubtype[].class);
然而,无论如何,这可能只是在引擎盖下循环和投射。
请参阅here。
答案 1 :(得分:0)
如果可能的话,我建议使用List
代替Array
。
答案 2 :(得分: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 []。
答案 3 :(得分:0)
如果您喜欢
,这样的事情是可能的public MySubtype[] convertType(MyObject[] myObjectArray){
MySubtype[] subtypeArray = new MySubtype[myObjectArray.length];
List<MyObject> subs = Arrays.asList(myObjectArray);
return subs.toArray(subtypeArray);
}