我知道泛型,但我不清楚这个语法。例如,在Collections.sort():Java在Collections中的静态方法需要说明吗?
public static <T> void sort(List<T> list, Comparator<? super T> c)
什么是静态<T>
返回类型为void前的意义是什么?
我知道泛型,但我不清楚这个语法。例如,在Collections.sort():Java在Collections中的静态方法需要说明吗?
public static <T> void sort(List<T> list, Comparator<? super T> c)
什么是静态<T>
返回类型为void前的意义是什么?
从sort
的方法签名:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
这<T>
定义了可以在方法定义中引用的任意通用类型T。
我们现在想说的是,该方法需要某种类型的List
(我们不关心它)T和另一种类型的Comparator
但这种类型必须是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'。你可以在课程顶部做到这一点,这意味着你到处都有相同的'T',或者你可以在特定的方法基础上做到这一点 - 就像这里。 – 2013-02-21 17:27:03
您可以按照没有实例Collections
。 sort()
方法是Collections
类的静态方法。
考虑之间的语法差别:
Collections col = new Collections();
col.sort(someCollection);
和
Collections.sort(someCollection);
的sort()
方法不必依赖于性能的一些可能的集合对象。因此,作为设计问题,最好声明为static
方法。
返回类型void之前静态
<T>
的意义是什么?
这是一种通用的方法,和<T>
是其类型参数。它表示,只要比较器能够比较此类型或其任何超类型的对象(Comparator<? super T>
),就会对包含任何类型对象(List<T>
)的列表进行排序。因此,编译器将允许您拨打sort
,例如通过List<Integer>
和Comparator<Number>
(因为Integer
是Number
的子类型),但不是List<Object>
和Comparator<String>
。
的<T>
被称为其在此处用于在抽象的排序方法正在操作的项目的类型的类型参数。你可以有类或方法的类型参数。这是为方法指定类型参数的语法,它必须在方法的返回类型之前。
我的问题应该已经明朗,我理解的“静态”部分的议题是通用。编辑该问题以仅突出显示通用 –
Ramp
2013-02-21 16:35:57