HI,
In the K&B book, page 577 there is the below code:
import java.util.*;
public class TestBadLegacy {
public static void main(
String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(4);
myList.add(6);
Inserter in = new Inserter();
in.insert(myList); // pass List<Integer> to legacy code
}
}
class Inserter {
// method with a non-generic List argument
void insert(List list) {
list.add(new Integer(42)); // adds to the incoming list
}
}
Sure, this code works. It compiles, and it runs. The insert() method puts an
Integer into the list that was originally typed as <Integer>, so no problem.
But�what if we modify the insert() method like this:
void insert(List list) {
list.add(new String("42")); // put a String in the list
// passed in
}
Will that work? The book states that Yes, sadly, it does! It both compiles and runs. No runtime exception. Yet, someone just stuffed a String into a supposedly type safe ArrayList of type <Integer>.
However, for me this has NOT worked I get a runtime exception java.lang.ClassCastException. Does anybody know whats going on? Is this a misprint in the book? Also if there is a link to corrections(if any) on the K&B SCJP5 book, I will be grateful. I have looked around but can't find it.
Many thanks.