0

there is Depot:

public class Depot
{
    private final int x, y;

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

Im making a list of it:

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

and they has to be passed to another method:

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

public void op(Depot[] depots)

but the **** row triggers an exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Depot;
John Smith
  • 6,129
  • 12
  • 68
  • 123

1 Answers1

2

Try below to get the array of same type as List

    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()]);
Saravana
  • 12,647
  • 2
  • 39
  • 57