有人可以向我解释为什么 Java 忽略对除 String
类之外的所有对象类型的迭代器进行转换的原因吗?
我有以下代码:
List list = new LinkedList();
list.add(new Object());
list.add(new String("First"));
list.add(10);
list.add(2.3);
我有两种情况:
1)
Iterator<Integer> crunchifyIterator = list.iterator();
while (crunchifyIterator.hasNext()) {
System.out.println((crunchifyIterator.next()));
}
结果是:
java.lang.Object@2a139a55
First
10
2.3
2)
Iterator<String> crunchifyIterator = list.iterator();
while (crunchifyIterator.hasNext()) {
System.out.println((crunchifyIterator.next()));
}
结果是:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
不知道是什么原因
最佳答案
System.out.println()
有多个版本
您正在向列表中添加不同类型的对象
List list = new LinkedList();
list.add(new Object()); // Type Object
list.add(new String("First")); // Type String
list.add(10); // Type Integer (not int)
list.add(2.3); // Type Float (not float)
在第一个循环中调用
System.out.println(Object o); // String, Interger, Float are all objects this causes no issues
在第二个循环中调用
System.out.println(String str); // This is where the casting fails, Object, Integer, and Float are not Strings.
这样做的原因是在运算符重载中调用的版本是在编译时(而不是运行时)确定的。
注意:
在实践中,除了列表的通用类型之外,您不应该在迭代器上使用通用类型。在您的情况下,类型默认为 Object。
关于Java:Cast on Iterator忽略除String类型以外的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37816946/