Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of raw type and data integrity

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.

like image 838
shazinltc Avatar asked Jun 23 '13 12:06

shazinltc


1 Answers

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.

like image 149
Boris the Spider Avatar answered Nov 03 '22 12:11

Boris the Spider