I'm trying to learn about the use of generic types and I've noticed something weird when I was experimenting with some lines of code.
The first piece of code is inside a class named "A":
public void func(int k, List list) {
list.add(9);
list.add(true);
list.add("a string");
}
The second piece of code is in a different class, inside the main function:
List<Integer> arr = new ArrayList<Integer>();
arr.add(14);
System.out.println(arr.toString());
a.func(8, arr);
System.out.println(arr.toString());
Running the code results in this lines being printed:
[14]
[14, 9, true, a string]
This got me pretty confused since arr
is an ArrayList
of type Integer
, how can it contain objects of type boolean
and String
? Is there a transformation of the list in the function func
to a raw type (which mean it becomes of generic type Object
)? And if so how is it possible since you cannot do this for example: List<Integer> arr = new ArrayList<Object>();
?
Would love some clarification on this, maybe it will help me grasp this subject of generic types better. Thanks!