【发布时间】:2014-12-04 09:01:05
【问题描述】:
我有这个代码:
List<Integer>[] intLists = new List[]{Arrays.asList(1)};
List<? extends Number>[] numLists = intLists;
numLists[0] = Arrays.asList(1.01);
double d1 = (Double)numLists[0].get(0); // ok
double d2 = intLists[0].get(0); // why java.lang.ClassCastException ?
double d2 = (Double)(Number)intLists[0].get(0); // I can do this way, but the question is not how but why
// the reason is in compiler! it adds implicin cast! after compilation code looks
double d2 = (Integer)intLists[0].get(0);
最后一行抛出的执行:
Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
为什么?
intLists 中的运行时元素的类型为 ArrayList,而不是 ArrayList<Integer>。 ArrayList 中的元素是 Double。
为什么不直接从列表中返回一个项目?
运行时没有Integer,怎么会出现?
【问题讨论】:
-
intLists包含Integers,除非您明确将其分配给double,否则您不能将其分配给。 -
@abkvandrd 在您的
intLists中。你能显示 ypurinLists数据吗? -
intLists - 是数组,它不包含整数!它包含 ArrayList ,其中包含 Double。
-
见:link 没有整数!