【发布时间】:2014-06-10 07:35:01
【问题描述】:
我创建了列表private final List<Double> prices
我有方法:
public Double getPrice(int i)
{
i--;
if (i >= this.prices.size())
{
return Double.NEGATIVE_INFINITY;
}
return this.prices.get(i);
}
而且看起来不错...但总是抛出:ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
经过一些测试,我发现:
我从配置创建此列表,但在配置中我使用不带点的数字,因此代码创建列表使用整数而不是双精度(ArrayList 内部包含整数)
但是为什么我可以将此列表转换为 List 而不会出现任何错误?
示例:
Integer a = 1;
Integer b = 1;
Integer c = 1;
Integer d = 1;
List<?> listI = new ArrayList<>(Arrays.asList(a, b, c, d));
List<Double> listD = (List<Double>) listI;
for (Object o : listD)
{
System.out.println(o.getClass().getSimpleName()); // Integer
}
System.out.println("done");
这段代码没有任何错误,但是从 Double 列表中打印 Integer,为什么不在 List<Double> listD = (List<Double>) listI; 中抛出 ClassCastException?
所以如果你尝试添加double num = listD.get(0); 然后抛出ClassCastException
【问题讨论】:
-
您注意到警告了吗?
标签: java arraylist casting integer double