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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With