ArrayList <Integer> automatically changes its type to ArrayList <String>
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]
List type = class java.lang.String
List type = class java.lang.Integer
Here is my code and result. My question is: how is it possible that an ArrayList of type Integer can store String objects? What type of list is it now? And what kind of mechanism is this?
Java generators do not actually modify the base class or object, they simply provide (mostly) compile-time semantics around them.
By passing an ArrayList<Integer> to a method that expects an ArrayList (which may contain something ), you will bypass the compiler's ability to provide you with such security.
The Java Generics Tutorial explains this, and why Java implements generics this way. This page , in particular, focuses on it:
Generalizations have been introduced into the Java language to provide more stringent type checks at compile time and to support general programming. To implement generics, the Java compiler applies style erasure to:
- Replace all type parameters in generic types with your borders or object if the type parameters are not limited. Thus, the obtained bytecode contains only ordinary classes, interfaces, and methods.
- Insert the type if necessary to maintain type safety.
- Creating bridge methods for preserving polymorphism in extended generic types.
Erasing styles ensures that no new classes are created for parameterized types; therefore, generics have no overhead at runtime.
What this does not say is that it also allows code written with generics (like your run ) to interact with code written without generics (like your readList ), which is important when adding a function to a very-installed language with huge library base (as it was when adding generics in Java).
When you declare:
private void readList(ArrayList list) you do not specify any type for this ArrayList , so by default it is of type Object .
Both String and Integer (virtually all classes in java) are subtypes of Object . Therefore, they can be added to the list.
Read more about generics without types here . Short types of generic types use only compile-time checks, so you donβt add the wrong types (which can later throw exceptions. In this case, your operations with String and Integer compatible, so, fortunately, there are no errors).