2 Replies Latest reply: Feb 9, 2010 4:08 PM by EJP RSS

    Generic method and multiple generics gives "Bound mismatch" compiler error

    843793
      Hi,

      I am trying to create a generic method that has generics that "extend" on each other and I get a compiler error. Below is a simple class I have to show the problem.

      public class TestGenericMethod {
           public TestGenericMethod() {
                test(); //This line is the error
           }
           
           public <A, B extends List<A>, C extends Map<A, B>> void test() {
                //Instance a new class
                TestGenericClass clazz = new TestGenericClass(null, null, null);
           }
      }

      public class TestGenericClass<A, B extends List<A>, C extends Map<A, B>> {
           A a;
           B b;
           C c;
           
           public TestGenericClass(A a, B b, C c) {
                this.a = a;
                this.b = b;
                this.c = c;
           }
      }

      In my real life example, I am simply trying to avoid the compiler warning:-
        • 1. Re: Generic method and multiple generics gives "Bound mismatch" compiler error
          843793
          Sorry, missed half my post.

          TestClass.TestGenericClass is a raw type. References to generic type TestClass.TestGenericClass<A,B,C> should be parameterized

          So when I parameterize the method using the same generics declaration, I would expect the compiler warning to dissapear, and for me to be able to call the method but this leads to the "Bound Mismatch" exception.

          The only way to fix is to change my clazz declaration to be:-

          TestGenericClass<Object, List<Object>, Map<Object, List<Object>>> clazz = new TestGenericClass<Object, List<Object>, Map<Object, List<Object>>>(null, null, null);

          Does anyone have an explanation why this is the case?
          • 2. Re: Generic method and multiple generics gives "Bound mismatch" compiler error
            EJP
            TestClass.TestGenericClass is a raw type.
            No it's not. It's a generic type.
            References to generic type TestClass.TestGenericClass<A,B,C> should be parameterized
            Correct, because it's a generic type.
            So when I parameterize the method using the same generics declaration, I would expect the compiler warning to dissapear
            No. You have to apply A, B, and C to the declarations of TestGenericType inside the method. It isn't done for you.
            The only way to fix is to change my clazz declaration to be:-
            No, the way to fix it is to fix the test() method.