我知道泛型,但我不清楚这种语法。例如,在 Collections.sort() 中:
public static <T> void sort(List<T> list, Comparator<? super T> c)
<T>
返回类型 void 之前的 static 有什么意义?
我知道泛型,但我不清楚这种语法。例如,在 Collections.sort() 中:
public static <T> void sort(List<T> list, Comparator<? super T> c)
<T>
返回类型 void 之前的 static 有什么意义?
方法签名来自sort
:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
这<T>
定义了一个可以在方法定义中引用的任意泛型类型 T。
我们在这里说的是该方法需要List
某种类型的 a(我们不在乎)T 和Comparator
另一种类型的 a,但这种类型必须是 T 的超类型。这意味着我们可以这样做:
Collections.sort(new ArrayList<String>(), new Comparator<String>());
Collections.sort(new ArrayList<Integer>(), new Comparator<Number>());
但不是这个
Collections.sort(new ArrayList<String>(), new Comparator<Integer>());
<T>
返回类型 void 之前的 static 有什么意义?
这是一个泛型方法,并且<T>
是它的类型参数。它表示,List<T>
只要比较器能够比较这种类型的对象或其任何超类型 ( Comparator<? super T>
),它就会对包含任何类型 ( ) 的对象的列表进行排序。因此,编译器将允许您调用sort
传递,例如 aList<Integer>
和 a Comparator<Number>
(作为Integer
的子类型Number
),但不能调用 aList<Object>
和 a Comparator<String>
。
您可以在不实例化的情况下进行排序Collections
。该sort()
方法是Collections
类的静态方法。
考虑以下之间的语法差异:
Collections col = new Collections();
col.sort(someCollection);
和
Collections.sort(someCollection);
该sort()
方法不必依赖某些可能的 Collections 对象的属性。因此,最好将 is 声明为一种static
设计方法。
称为类型参数,<T>
此处用于抽象排序方法正在操作的项目的类型。您可以为类或方法设置类型参数。这是为方法指定类型参数的语法,该参数必须在方法的返回类型之前。