Java-syntax for explicitly specifying generic arguments in method calls

前端 未结 3 1489
我寻月下人不归
我寻月下人不归 2020-12-05 09:01

What is the syntax for explicitly giving the type parameters for a generic Java method?

3条回答
  •  萌比男神i
    2020-12-05 09:48

    A good example from java.util.Collection of specifying a generic method which defines its own generic type is Collection.toArray where the method signature looks like:

     T[] toArray(T[] a);
    

    This declares a generic type T, which is defined on method call by the parameter T[] a and returns an array of T's. So the same instance could call the toArray method in a generic fashion:

    Collection collection = new ArrayList();
    collection.add(1);
    collection.add(2);
    
    // Call generic method returning Integer[]
    Integer[] ints = collection.toArray(new Integer[]{});
    
    // Call generic method again, this time returning an Number[] (Integer extends Number)
    Number[] nums = collection.toArray(new Number[]{});
    

    Also, see the java tutorial on generic type parameters.

提交回复
热议问题