0

List<Number> and List<Integer> are different type: if that is the case why overloading the following method does not compile?

public static  void iMethod(List<Number> nList){
    System.out.println(nList);
}


public static  void iMethod(List<Integer> iList){
    System.out.println(iList);
}

error:

Erasure of iMethod<List<integer>> is same as another method in class

The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
  • 1
    Since Java suffers from "generic type erasure", don't you think the two methods will look exactly the same after compiling? –  Oct 30 '18 at 12:48
  • Both iList and nList in the method parameter is object reference of List Type. – Mdumanoj Oct 30 '18 at 12:52
  • I am studying generics, i understand that Type parameter `T` will be erased but note sure if we specify the type like `integer`, it will do the same. – The Scientific Method Oct 30 '18 at 12:52
  • 1
    List will receive `Integer` as its generic type `T`. So yes, both gets erased. – Tom Oct 30 '18 at 12:55

2 Answers2

3

Java has this thing called "type erasure" which causes problems like this when compiling generic code like this. When compiled, List<Number> and List<Integer> are both just plain List.

jwismar
  • 12,164
  • 3
  • 32
  • 44
  • I understand that Type parameter `T` will be erased but not sure if we specify the type like `Integer`, it will do the same. – The Scientific Method Oct 30 '18 at 12:55
  • what do you mean *just plain List* – The Scientific Method Oct 30 '18 at 12:58
  • As far as the JVM is concerned, generics don't really exist. It's kind of a bolted-on syntactical thing. At the byte code level, the only thing that exists is List. List, Set, Map all go through type erasure and become List, Set and Map, respectively. – jwismar Oct 30 '18 at 13:01
  • *thing that exists is List.* you mean `List`? – The Scientific Method Oct 30 '18 at 13:05
  • No, I mean unparameterized List. At least conceptually. In the actual implementation I have installed, it's actually specified as List, because the old, unparameterized List class (that, yes, took Object elements) doesn't seem to exist any more. But conceptually it's still in there. – jwismar Oct 30 '18 at 13:15
  • But if you try to cast it, it won't let you :D : `incompatible types: Map cannot be converted to Map` – White_King Jan 30 '22 at 16:33
2

All your generic code is strictly for the compiler. Through a process called "type erasure," the compiler does all of its verifications on your generic code and then strips the type information out of the class bytecode.

In other words, even though you WROTE

List < Integer > myList = new ArrayList<Integer>();

By the time the compiler is done with it, the JVM sees what it always saw before Java 5 and generics:

List myList = new ArrayList();
DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42
Parth Lukhi
  • 181
  • 8