Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why this is not overloading? [duplicate]

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
like image 232
ankit Avatar asked Nov 29 '22 00:11

ankit


1 Answers

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.

like image 174
chrylis -cautiouslyoptimistic- Avatar answered Dec 05 '22 07:12

chrylis -cautiouslyoptimistic-