2016-09-22 67 views
0

有仓库:Java,将ArrayList转换为数组(toArray)不能被铸造?

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()]);