Abelo Abelo - 5 months ago 18
Java Question

Java: Cast on Iterator ignore integer except String type

Somebody can explain me the reason that Java ignore the cast for interator for all object types except the String class.

I have the next code:

List list = new LinkedList();
list.add(new Object());
list.add(new String("First"));
list.add(10);
list.add(2.3);


and 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()));
}


and 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 is the reason.

Thank you very much

Answer

There are multiple versions of System.out.println()

You are adding different types of Objects to the list

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)

In the fist loop it calls

System.out.println(Object o);  // String, Interger, Float are all objects this causes no issues

In the second loop it calls

System.out.println(String str);  // This is where the casting fails, Object, Integer, and Float are not Strings.

The reason for this is in operator overloading the version called is determined at compile time (not runtime).

Note:

In practice you should not be using a generic type on your iterator other then the generic type of your List. In your case the type defaults to Object.