Can somebody explain to me the reason why Java ignores the cast for the iterator on all object types except the String class?
I have the following code:
List list = new LinkedList();
list.add(new Object());
list.add(new String("First"));
list.add(10);
list.add(2.3);
I have two cases:
1)
Iterator<Integer> crunchifyIterator = list.iterator();
while (crunchifyIterator.hasNext()) {
System.out.println((crunchifyIterator.next()));
}
The result is:
java.lang.Object@2a139a55
First
10
2.3
2)
Iterator<String> crunchifyIterator = list.iterator();
while (crunchifyIterator.hasNext()) {
System.out.println((crunchifyIterator.next()));
}
The result is:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
I don't know what the reason is.