1

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.

0

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi cyroxis, but if I write this Iterator<Integer> crunchifyIterator = list.iterator(); is permited and if I try whit that Iterator<String> crunchifyIterator = list.iterator(); throws a exception
@Abelo I updated my answer to give some more clarity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.