public void run(){
setFont("Courier-24");
//Define list as ArrayList<Integer>
ArrayList<Integer> list = new ArrayList<Integer>();
readList(list);
}
private void readList(ArrayList list){
list.add("Hello");
list.add(2);
println("list = "+list);
println("Type of list = "+list.get(0).getClass());
println("Type of list = "+list.get(1).getClass());
}
Result:
list = [Hello, 2]
Type of list = class java.lang.String
Type of list = class java.lang.Integer
Here is my code and result. My question is, how is it possible that ArrayList of type Integer can store String objects? What's the type of list now? And what mechanism is this?
Java's generics don't actually change the underlying class or object, they just provide (mostly) compile-time semantics around them.
By passing an
ArrayList<Integer>
into a method expecting anArrayList
(which can hold anything), you're bypassing the compiler's ability to provide you with that type safety.The Java Generics Tutorial explains this, and why Java implements generics this way. This page, in particular, focusses on it:
What that doesn't say is that this also allows code written with generics (like your
run
) to interact with code written without generics (like yourreadList
), which is important when adding a feature to a very-well-established language with a huge library base (as they were when adding generics to Java).