4

配列をある型から別の型に変換したい。以下に示すように、最初の配列内のすべてのオブジェクトをループし、それらを 2 番目の配列型にキャストします。

しかし、これはそれを行うための最良の方法ですか?各アイテムのループとキャストを必要としない方法はありますか?

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 に答える