Mixing generics with legacy code
List<String> words = new ArrayList<String>();
words.add("house");
words.add("book");
addSth(words);
private void addSth(List list) {
list.add(new Integer(6));
}
- the above code compiles (but with warnings) and can work fine, at least to the place of addition (if the object was later retrieved from the
Listit could break down, e.g. words would be treated asList<String>but Integer objects was retrieved) - this code is unsafe - generic code is only for the compiler purposes; JVM knows nothing about what really the
Listholds - at runtime both legacy and Java 5 code (with generics) look the same, like pre-generic version
List<String> words = new ArrayList<String>();
System.out.println(words instanceof List<String>); // WON'T COMPILE
The above code won’t compile since all instances of a generic class have the same runtime class, regardless of their actual type parameters.
Instead, you should do as below:
List<String> words = new ArrayList<String>();
System.out.println(words instanceof List); // OK
This is also worth a look:
Collection<String> words = new ArrayList<String>();
List<Integer> numbers = new ArrayList<Integer>();
System.out.println(words.getClass() == numbers.getClass()); // produces "true"





