0

Please see the code below.

import java.util.ArrayList;
import java.util.List;
public class Generics {

public static void append(List list) {
   list.add("ABCD"); 
}

public static void main(String[] args) {
    List<Integer> intList = new ArrayList<Integer>();
    append(intList);
    System.out.println(intList.get(0));
}
}

In list.add("ABCD"), it is expected that run-time exception will occur, since ABCD is not an Integer. I know that 'list' is of raw type, so list.add() won't give any compilation issues, but it should break while running the program, right?

And again - System.out.println(intList.get(0)) - 'intList' is the list of Integers, and it is expected to return integer value, but 'ABCD' is not an Integer. Why this is also working?

Can you please clear my doubts, why this code is working with out any issues?

Sanooj
  • 29
  • 1
  • 4
  • 1
    Why should it break? There is nothing "in" that list that will cast to `Integer` and `System.out.println(intList.get(0))` also won't requires a cast to `Integer`, since it will always use `println(Object)`. – Tom Jul 14 '16 at 11:33
  • 3
    See: [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Jesper Jul 14 '16 at 11:34
  • that is because you are using List as an argument in the method append() . Provide ArrayList as an argument , it will then only accept integers , and no string . – Saurabh Chaturvedi Jul 14 '16 at 11:39
  • @AndyTurner Or when one passes `inList.get(0)` to a method which actually expects `Integer` or `int`. – Tom Jul 14 '16 at 11:40

0 Answers0