Abelo Abelo -5 years ago 202
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"));

and I have two cases:


Iterator<Integer> crunchifyIterator = list.iterator();
while (crunchifyIterator.hasNext()) {

the result is:



Iterator<String> crunchifyIterator = list.iterator();
while (crunchifyIterator.hasNext()) {

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 Source

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).


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download