0

Today my brain was broken, I saw this working code in our project:

`public static void main(String[] args) {
    List<Integer> list2 = new ArrayList();
    changeList(list2);
    changeList2(list2);
    System.out.println(list2);
}
public static void changeList(List list) {
    list.add("asdsadf");
    list.add("jhbsd");
    list.add("dchbjhdsa");
}
public static void changeList2(List list) {
    list.add(1L);
    list.add(2L);
    list.add(3L);
}`

how is it possible? I always think that ArrayList can contains only one type of objects

  • 1
    It is possible, but it's the gateway to A LOT of bugs. That's also why generics were introduced and people think a collection can only contain elements of 1 data-type while it's the generics that limit us from doing it. – Nico Van Belle Mar 06 '21 at 07:23
  • The parameter of both `changeList` functions have no generics. So despite having initiated a `List` in your `main`, the Generic isn't passed into the functions; making a `List` out of `List`. – Sorin Mar 06 '21 at 07:27

0 Answers0