2016-09-22 1 views
0

がデポがある:それのリストを作るArrayListを配列(toArray)に変換するJavaをキャストすることはできませんか?

public class Depot 
{ 
    private final int x, y; 

    public Depot(int x, int y) 
    { 
     this.x = x; 
     this.y = y; 
    } 
} 

イム:

ArrayList<Depot> depots = new ArrayList<>(); 
depots.add(new Depot(1, 2)); 
depots.add(new Depot(5, 7)); 

、彼らは別のメソッドに渡さなければなりません:

Object[] d2 = depots.toArray(); 
op((Depot[]) d2); **** 

public void op(Depot[] depots) 

が、****行は例外をトリガーします:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Depot; 

答えて

1

リストと同じタイプの配列を取得しようとすると

List<Depot> depts = new ArrayList<Depot>(); 
    depts.add(new Depot(1, 2)); 
    depts.add(new Depot(1, 2)); 
    depts.add(new Depot(1, 2)); 
    Depot[] depots = depts.toArray(new Depot[depts.size()]); 
関連する問題