2

I'm playing with generic and I have a code that I can't undestand.

public static void main(String[] args) {
    ArrayList<Integer> list=new ArrayList<Integer>();
    list.add(1);

    System.out.println(list);
    t(list);
    System.out.println(list);
}

static void t(List list){
    list.add("test2");
    list.add(3);
}

So, it's compiled and it works. I understand why the method t works .But I can realize why it is added to the main list which has stric generic type. Thanks

xyz
  • 5,228
  • 2
  • 26
  • 35

3 Answers3

3

This is the problem with using raw types in Java. In fact, the compiler should have warned you about unchecked calls to add in the t method. This warning means "type safety" isn't assured, and as you've shown, it isn't assured.

It compiles for backwards compatibility reasons, and it runs because of type erasure, which means that at runtime the ArrayList just holds Objects anyway.

Note that this can result in a runtime ClassCastException if you were to attempt to extract the element corresponding to the String with

Integer oops = list.get(1);  // Cannot cast from `String` to `Integer`
rgettman
  • 176,041
  • 30
  • 275
  • 357
2

Because of type erasure. At runtime generics are deleted so when you pass the list to the static method, it does not fail because it's assuming a list of Objects.

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

  • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.

More on type erasure: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

dierre
  • 7,140
  • 12
  • 75
  • 120
0

The method "t" takes as parameter type raw List (not List of integers). So you can put there anything you want, because by default each List is List of Objects. But this is a really bad practice.

Yurii Bondarenko
  • 3,460
  • 6
  • 28
  • 47