This discussion is archived
4 Replies Latest reply: Aug 20, 2007 2:27 AM by 807605 RSS

Overloading with Java 1.5 Generics

807605 Newbie
Currently Being Moderated
Hi,

I don't understand why the following code won't compile:
public class Foo {

        public void size(List<Integer> list) {

     }

     public void size(List<String> list) {

     }
}
The error "Duplicate method". From some reason, it treats List<Integer> as the same type as List<String>

Why is that?

Thanks,

Asaf
  • 1. Re: Overloading with Java 1.5 Generics
    800322 Newbie
    Currently Being Moderated
    Because a List is a List.
  • 2. Re: Overloading with Java 1.5 Generics
    807605 Newbie
    Currently Being Moderated
    Because the compiler actually removes all the generic information from the binary files, meaning that these two methods end up having the same signature. If you do a search on erasure and Java generics on Google, you'll find a more in depth explanation.
  • 3. Re: Overloading with Java 1.5 Generics
    807605 Newbie
    Currently Being Moderated
    It's another result of the policy of erasure - that generics information is really compile time only. At runtime a List is a List, hence generics information can't be used to select method signatures.
  • 4. Re: Overloading with Java 1.5 Generics
    807605 Newbie
    Currently Being Moderated
    Which method to call is a compile-time decision, so the absence of run-time type information alone doesn't really explain everything. But it's true, Java erases type information before deciding which method to call, so it wouldn't be able to decide between the two, and therefore forbids having both.

    Imagine I write this:
    Foo myFoo = new Foo();
    List myList = new ArrayList();
    myFoo.size(myList);
    I deliberately mix non-generic code with your generic code. It's bad style, but legal. Now which of your methods would you expect the compiler to choose for the call? There isn't really a convincing choice, is there? I guess that this is one of the reasons behind forbidding the code that you wrote.

    You may try this instead:
    public class Foo {
     
         public void size(List<?> list) {
     
         }
    }
    Message was edited by:
    OleVV