I'm trying to learn about using generic types, and I noticed something strange when I was experimenting with some lines of code.
The first part of the code is inside the class named "A":
public void func(int k, List list) { list.add(9); list.add(true); list.add("a string"); }
The second part of the code is in another 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());
Executing the code prints the following lines:
[fourteen]
[14, 9, true, string]
This puzzled me, since arr is an ArrayList type Integer , how can it contain objects of type boolean and String ? Is there a conversion of the list in the func function to a raw type (which means that it becomes a generic Object type)? And if so, how is this possible, since you cannot do this, for example: List<Integer> arr = new ArrayList<Object>(); ?
I would like to clarify this, perhaps it will help me better understand this subject of generic types. Thanks!
source share