Search code examples
javagenericswildcardtype-parameter

Java generics : wildcard and type parameter syntax when defining generic class


In the following generic method declaration examples, I think these two method declaration are the same in terms of and because of their accepting the same type of arguments.

public static <T extends List<? extends Number>> void fun(T arg){}
public static void foo(List<? extends Number> arg){}

OK, then why using the following syntax to define generic class is not allowed?

public class foo<List<? extends Numer>> {}

According to oracle's Java tutorial, is it because I can only use the syntax class name<T1, T2, ..., Tn> { /* ... */ } to define generic classes? And Java also provide an extra syntax sugar to define generic methods?

So, If I want to define a generic class like public class foo<T extends List<U extends Number>> to make use of T and U, I can only do it in the following way: public class foo<U extends Number, T extends List<U>>? There are no succinct ways to do it?

Thanks!


Solution

  • From your original intent... the following is a valid generic class

    public class MyClass<T extends List<? extends Number>> {}
    

    It could be used as follows...

    public class MyClass<T extends List<? extends Number>> {
        T myList;
    
        public T getMyList() {
            return myList;
        }
    
        public void setMyList(T myList) {
            this.myList = myList;
        }
    }
    
    public class Tester {
        public Tester() {
            MyClass<ArrayList<Number>> list = new MyClass<>();
            list.setMyList(new ArrayList<>());
            list.getMyList().add(new Integer(2));
            list.getMyList().add(new Long(3));
        }
    }