我对 Java 中的泛型用法还很陌生。
在Collections.java
类中遇到以下函数进行排序
// Sorting based on Comparable
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
// Sorting based on Comparator
public static <T> void sort(List<T> list, Comparator<? super T> c) {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set(a[j]);
}
}
我想了解的是:
为什么在基于
Comparable
的排序函数中参数化ListIterator
以及为什么使用 rawListIterator
在基于Comparator
的排序函数中?在
for
循环中,为什么基于Comparable
的排序函数需要类型转换(到T
)以及为什么转换是在基于Comparator
的排序函数的for
循环中不需要吗?
我认为以下代码对于基于比较器的排序函数来说具有更多的类型安全性:
public static <T> void Sort(List<T> list, Comparator<? super T> c) {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
最佳答案
why raw ListIterator is used in sort function based on Comparator.
您无法创建 ? super T[]
类型的数组所以它会创建一个 Object[]
并使用那里的原始类型。
In the for loop why is Type Casting ( to T) needed in sort function based on Comparable and why casting is not necessary in for loop of sort function based on Comparator
在第一种情况下,您有 ListIterator<T>
只能set(T)
在第二种情况下,你有 ListIterator
可以设置任何对象。
关于java - Collections 实用程序类中排序函数的实现比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11879730/