1

I am very confused as to why the Integer type Arraylist is able to add a String to it. As shown, below,"("0067")" is added to the list in the addtolist(List list) method, and since it is a String the code should throw an error, but it doesn’t. Can anyone explain why this code runs successfully?

//test program    


import java.util.ArrayList;
import java.util.List;

public class listing {


public static void main(String[] args) {
    List<Integer> lst = new ArrayList<Integer>();

    addToList(lst);

    System.out.println(lst.get(0));
}

public static void addToList(List list) {
    list.add("0067");
}
}
Christopher Jobling
  • 1,048
  • 2
  • 7
  • 10

3 Answers3

4

Look at the method signature:

public static void addToList(List list)

list is a raw type, enabling warnings should warn you something like:

List is a raw type. References to generic type List should be parameterized

To have a stronger type checks at compile time, you need to change it to:

public static void addToList(List<Integer> list)
Maroun
  • 94,125
  • 30
  • 188
  • 241
0

The parameter type of the list in addToList() is not generic. This means that inside that method you can add any object to that list without producing a compiler error because only the generic type of the parameter is checked, not the one of the passed list.

Now why does this code also work at runtime? While compiling the generic type information is erased. So basically every list is a List<Object> at runtime. If you take a look at your code again while keeping this in mind, you will see that it works. Also because there is a println which takes Object as parameter.

An example that would compile but not run would be if you added

Integer foo = lst.get(0);
André Stannek
  • 7,773
  • 31
  • 52
0

In your code

public static void addToList(List list) 

you don't get an compiler warning because the paramter list, is not generic. That means it is equivalent to List<Object> list. You would get an error at runtime at first try to insert an element into the list.

Just change to

public static void addToList(List<Integer> list)

and you will get a compile time errror.

AlexWien
  • 28,470
  • 6
  • 53
  • 83