It is presumably because of erasure; if Java had generics from the start this might not have happened. You might see the two parameters as different type, but when the <> is removed the JVM will see two methods with Map as the type of their parameters. There is more about erasure in the Java Tutorials and Angelika Langer's website. [ December 05, 2008: Message edited by: Campbell Ritchie ]
hello Michael, you are trying to do a method overload but you're creating a method with the same signature, because the generics doesn't affect the signature of a method, it's just used for compile time checking. Just try to use another signature to solve the problem.
They can't because of backwards compatibility. Generics information simply is not stored in byte code.
You can cheat though, by giving the methods a different return type. Although after erasure they both have the same name and parameters, it will be different in byte code because the entire signature is not the same - the return type is different.
Rob: You can cheat though, by giving the methods a different return type.
And this "feature" is called co-variant return types! This was also introduced in JDK 5. Before that it was not possible to define two methods with the same name and arguments and different return types.
Well actually Nitesh, this has nothing to do with co-variant return types.
Co-variant return types are used when you are overriding a method, and are narrowing the return type. For example, what Sun should have done with java.util.Date:
Because any calling method expects an Object, a Date object will be assignable.
The trick I mentioned only works with methods with generics, and involves the actual method signature in byte code. The only reason why the compiler doesn't allow methods with the same name and parameter types but different return types without generics is ambiguity - it doesn't know which one to choose. With generics the ambiguity is not there* and the compiler can fill in the details.
With the following methods:
the actual method signatures for the JVM are different:
* Of course if both Maps are Map<String,String> there is still ambuigity, but you get the picture. [ December 08, 2008: Message edited by: Rob Prime ]
Originally posted by Nitesh Kant: I should probably keep quiet about things i do not know completely! (and i know that i do not know ) Thanks.
Well if it helps, I think you _should_ post. It encourages the discussion and then we all can learn/benefit from that. It may help to say 'I'm not really 100% sure' if you "didn't write the book on it" but apart from that post away!!
I often post my best guess and the best thing about this place is that someone inevitably comes along and clarifies any mistakes for me!