What happens at compile time when you try to cast a LinkedList to a LinkedList<String>?

In the following, I get a runtime exception on line 5, not on line 4. What is that cast actually doing? Any insight or links to relevant reading would be awesome.

List list = new LinkedList();
list.add(new Date());
list.add("Hello");
List<String> list2 = (List<String>)list;
String value = list2.get(1);
Jon Skeet
people
quotationmark

What is that cast actually doing?

Nothing, at execution time. That's why you'll get a warning saying that it's an unchecked cast - it's not really checking anything, because the object itself (at execution time) has no concept of being a List<String> - it's just a list. If you had:

Object x = ...;
List<String> list = (List<String>) x;

then that would check that x refers to a list of some kind... but it wouldn't check the "stringness" of the list.

This is the way Java generics works, unfortunately :(

people

See more on this question at Stackoverflow