Raw Type and Data Integrity List

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"); } 

Compiles and prints the result

[1, blabl]

My understanding:

The control variable 'integers' has the address (say 111) of the arraylist object, which is passed to the addToList method. Thus, in the addToList method, list0 points to the same address that has an object (which is an arraylist of type Integer), and a string is added to this arraylist object.

How can I add a String to an integer type arraylist? Isn't that a data integrity issue?

Update

The answer below and this answer helped. Thanks.

+6
source share
1 answer

This is a classic example of Type Erasure . In Java, generic files are deleted at compile time and replaced with sheets.

This means that you can do this, but you get a ClassCastException :

 Integer myInt = integers.get(1); 

In fact, the compiler should warn you when you do this, because you cause the List<Something> to be dropped implicitly in the List when the method is called. The compiler knows that it cannot verify type safety at compile time.

+6
source

Source: https://habr.com/ru/post/947934/


All Articles