In this example
public static void main(String[] args) {
List<Integer> integers = new ArrayList<Integer>();
integers.add(1);
addToList(integers);
System.out.println(integers);
}
public static void addToList(List list0){
list0.add("blabl");
}
This compiles and prints a result
[1, blabl]
My understanding is:
The reference variable 'integers' has an address (say 111) of the arraylist object which is being passed to the addToList method. So in the addToList method list0 points to the same address which has the object (which is an arraylist of type Integer) and a string is added to this arraylist object.
How is it possible to add a String to the arraylist of type Integer? Isn't that a data integrity issue?
Update
The answer below and this answer helped. Thanks.
This is a classic example of Type Erasure. In Java, generics are deleted at compile time and are replaced by casts.
This means that your can do that, but you will get a ClassCastException
when you did:
Integer myInt = integers.get(1);
In fact the compiler should warn you when you do that because you are implicitly casting List<Something>
to List
when you call the method. The compiler knows that it cannot verify the type safety at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With