8

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) {}
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
asela38
  • 4,546
  • 6
  • 25
  • 31

3 Answers3

16

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.)

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • Method resolution is done at compile time, so the Java language could be extended to allow this sort of overloading without reification. However, it's probably simpler to insist on better method naming. – Tom Hawtin - tackline Oct 06 '10 at 02:29
  • Yes, but the objective was to not break the binary format (legacy code had to keep working, even with new code) – Sean Patrick Floyd Oct 06 '10 at 04:49
1

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) {}

Favonius
  • 13,959
  • 3
  • 55
  • 95
0

You got the compiler error because the methods are not overloaded properly. Both methods have a parameter of Set type that makes both the methods identical for he compiler.

Amit
  • 466
  • 6
  • 11