Java: Cast on Iterator ignore integer except String type
Java: Cast on Iterator ignore integer except String type
有人可以向我解释为什么 Java 忽略除 String
class 之外的所有对象类型的迭代器的转换吗?
我有以下代码:
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()
您正在向列表中添加不同类型的 Objects
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 忽略除 String
class 之外的所有对象类型的迭代器的转换吗?
我有以下代码:
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()
您正在向列表中添加不同类型的 Objects
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.