Generics query

In K&B pg 603 , it is explained that when we try to use legacy code (method) which modifies the type-safe list, the complier
shows warnings and runs well without exception. But i noticed that on my compiler( Dr JAVA) i am getting ClassCastException .
Could anyone please tell ??
Here goes the code :-

I think you misinterpreted the statement. I believe the book is trying to say that all you will get is a compiler warning -- ie. you will not get any runtime errors about the (due to the) mixing generics and non-generics.

Other runtime errors caused by problems from mixing generics and non-generics is a different story.

Will that work? Yes,sadly, it does! It both compiles and runs. No runtime Exception. Yet, someone just stuffed a String into a supposedly type safe
Array List of type <Integer> How can that be ???

Actually i removed Line 1 and Line2 to and it worked fine , ie Runs without Exceptions. So i thought that since i am using it thats why there was an exception
But, then again another brain neuron hits my mind that, i am using Object ref in for loop then there should not be any issue like that.....

Please run the above code in your compiler ....May be some compiler issue ???

From the above for-each loop, we can apparently think that the element of the myList, what is either String or Integer should assign into Object reference normally. But, I feel there is an intermediate step that try to cast the element of the myList into the actual parameter type with which the myList is declared and instantiated. And then the reference of the element is assigned into the Object reference.

Another part of the story is that if we use Iterator<E> instead of for-each loop then we will get the expected result. For instance,

I think, there is a internal mechanism in the foreach loop, when we are using it with the Generics. Because, the code below works ...

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|

Unmesh Chowdhury
Ranch Hand

Joined: Jun 20, 2010
Posts: 45

posted Jun 28, 2010 06:37:01

0

In your case, for-each loop is used for raw type, that is, the list is not generic. So, in this case the compiler doesn't treat the list specially. The context of the previous for-each loop and the context of your for-each loop is not same.