17

Why isn't this allowed and treated as same signature?

public Object myMethod(Map<String, String[]> values) {
   return this;
}

public Object myMethod(Map<String, String> values) {
   return this;
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
user1236048
  • 5,542
  • 7
  • 50
  • 87

2 Answers2

17

The urban myth answer is:

Because type erasure causes the generics information to be lost. At runtime, those methods appear identical.

Map<X, Y> becomes just Map.

However, the actual answer appears to be more complex. See this excellent answer from a duplicate question. The compiler is actually quite capable of selecting the correct overloaded method given the supplied arguments, however the requirement to support legacy non-generics-aware code has forced the javac developers to forbid it.

Community
  • 1
  • 1
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • 1
    But overloading is done at compile time. – artbristol Apr 04 '13 at 09:27
  • @artbristol You are quite correct actually. Having read in more detail the answers in the duplicate I linked, it is apparently a language syntax restriction. Sadly I can't delete this answer now that it's accepted, but I'll include a link to the other answer in the meantime. – Duncan Jones Apr 04 '13 at 09:47
6

This is because of Type Erasure. Type Erasure removes most of the generics information at compile time. So above code after compilation would be

public Object myMethod(Map values) {
   return this;
}

public Object myMethod(Map values) {
   return this;
}

So both the methods are identical at runtime.

Sachin Gorade
  • 1,427
  • 12
  • 32