Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading with generics [duplicate]

Tags:

java

generics

Where I try to create two static overloading methods I got an compilation error. Can anyone explain this?

public class A {
 public static void a(Set<String> stringSet) {}
 public static void a(Set<Map<String,String>> mapSet) {}
}
like image 729
asela38 Avatar asked Oct 05 '10 06:10

asela38


2 Answers

The reason is type erasure. Generics are not stored in the classes, they are compile-time info only, so at runtime, the two methods are identical and hence there is a naming conflict.

Reference

These three methods are actually identical (read: they produce identical bytecode):

public static void a(Set plainSet) {}
public static void a(Set<String> stringSet) {}
public static void a(Set<Map<String,String>> mapSet) {}

If you really want to have two separate methods, you must provide different method signatures (e.g. different method names, an additional parameter for one of the methods etc.)

like image 106
Sean Patrick Floyd Avatar answered Nov 06 '22 15:11

Sean Patrick Floyd


From the point of view of the methods parameters Set<String> and Set<Map<String,String>> are the same, because all instances of a generic class have the same run-time class (Set in your case), regardless of their actual type parameters. Therefore you will get a erasure error. Also at runtime both will look like... public static void a(Set stringSet) {} AND public static void a(Set mapSet) {}

like image 35
Favonius Avatar answered Nov 06 '22 16:11

Favonius