4 Replies Latest reply on Aug 20, 2007 9:27 AM by 807605

    Overloading with Java 1.5 Generics


      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?


        • 1. Re: Overloading with Java 1.5 Generics
          Because a List is a List.
          • 2. Re: Overloading with Java 1.5 Generics
            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
              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
                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();
                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: