4

I have two methods as follows

public void add(List<String> strs) {...}

public void add(List<Integer> ints) {...}

I get compilation errors, so my question is why this is not overloading, and what is the advantage of using generics then?

This is the error that I get:

Method add(List<Integer>) has the same erasure add(List<E>) as another method in type Child
chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
ankit
  • 4,919
  • 7
  • 38
  • 63

5 Answers5

16

Java Generics are a compile-time only language feature; the generic types (such as String and Integer here) are erased during the compilation, and the bytecode only includes the raw type, like this:

public void add(List strs) {...}

Because of this, you can't have multiple methods whose signatures differ only in the generic types. There are a few ways around this, including varargs and making your method itself generic, and the best approach depends on the specific task.

The advantage of generics is that inside a method that takes a List<String>, you can add or remove elements from the List and treat them as just String objects, without having to add explicit casting everywhere.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
4

Generic types are erased at runtime. SO your public void add(List<String> strs) and public void add(List<Integer> ints){...........} are the same type , the compiler just places compile-time restrictions on what you can do with them.

pratim_b
  • 1,160
  • 10
  • 29
2

When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for T is) and verifies at compile time that you're doing the right thing, but the emitted code again just talks in terms of java.lang.Object - the compiler generates extra casts where necessary. At execution time, a List<Integer> and a List<String> are exactly the same; the extra type information has been erased by the compiler.

Thus you get compilation error.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

In Java you can do this(overloading) as follows with parameter list contains with List.

 public void add(List strs){

 }

If you use deferent type of List with same method name, it will consider as same method.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

Keep in mind, that the JVM will not decide which method to call at runtime. As opposed to virtual methods / method overriding resolution of overloaded methods are done at compile time. The Java Tutorials on method overloading even points out that "Overloaded methods should be used sparingly...".

Nomesh Gajare
  • 855
  • 2
  • 12
  • 28