Isn't this sort of thing possible in Java? I would have thought that the types "List<String>" and "List<Integer>" were sufficiently different to allow method overloading.
Is the only solution to give the methods differernt names?
Harsha Smith wrote:You are not overloading the method here. Method Overloading mean same method name but different parameters. The return types can either be same or different.
Generics Type erasure. List<String> list and List<Integer> list are one and the same.
I see, thanks - not quite the same as what I'm used to. I would have thought that "List<String>" and "List<Integer>" were different - therefore method overloading would be possible.
I'll just rename my methods then.
Seems a little odd though that Java seems to be telling me that "List<String>" and "List<Integer>" are the same here, but if I try the following, Java tells me they are not the same!
Peter Kirk wrote:Seems a little odd though that Java seems to be telling me that "List<String>" and "List<Integer>" are the same here, but if I try the following, Java tells me they are not the same!
In Java, because of certain compromises made when generics were introduced into the language, the generic information only exists at compile-time. At run-time, the information is lost. That's why those codes are considered the same - they have the same "erasure", meaning they have the same signature once the generic info is erased.
Rob Spoor wrote:In other words, at runtime all that remains is And those are certainly the same.
Yes thanks, they are the same - and I have now come to understand a little more of Java's handling of generics. It appears that generics is not a runtime thing in Java, only compile time. The JVM has no idea of generic types, and the generics we use in code is only syntactic sugar. Apparently this is in part (or mostly?) due to a neccessity of maintaining backward compatibility. I was already aware what "method overloading" was - just not aware of Java's generic interpretation. I prefer the .net/c# idea, where something like my original method overloading would compile and run fine. But it's not a biggie - just a "surprise" when you don't know.