2016-09-22 3 views
0

есть Depot:Java, преобразование массива ArrayList в массив (toArray) невозможно выполнить?

public class Depot 
{ 
    private final int x, y; 

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

Im сделать список:

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()]); 
Смежные вопросы