【问题标题】:Java, converting ArrayList to array (toArray) cannot be casted? [duplicate]Java,将ArrayList转换为数组(toArray)不能强制转换? [复制]
【发布时间】:2016-09-22 08:27:34
【问题描述】:

有仓库:

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;

【问题讨论】:

    标签: java


    【解决方案1】:

    尝试下面获取与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()]);
    

    【讨论】:

      猜你喜欢
      • 2011-04-24
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2019-06-09
      • 1970-01-01
      相关资源
      最近更新 更多