[英]Questions about implementing the Comparable interface
我是第一次教Java編程課程。 我的教科書使用Comparable
,但是網上看到的大多數示例都使用Comparable<T>
。 它們是否使用兩個不同的接口?
與此相關的是,當我在Student類中編寫compareTo()方法時,教科書使用
public int compareTo(Object other){
if (! (other instance of Student))
throw new IllegalArgumentException("Parameter must be a Student");
return name.compareTo( ((Student)other).getName() );
}
我看到如下的compareTo()的其他示例:
public int compareTo(Student otherStudent){
return name.compareTo( otherStudent.getName() );
}
如果Student類實現Comparable<Student>
這第二種構造應該使用什么?
最后,我的教科書提供了有關如何編寫通用對象排序算法的提示。 我到達以下。 它可以工作,但是會發出“未經檢查或不安全的操作”警告。 有沒有一種方法可以編寫“安全”的通用排序算法?
private static void bubbleSortObjects(Comparable[] array)
{
int i = 0;
boolean swapped = true;
while (swapped && i < array.length - 1)
{
i++;
swapped = false;
for (int j = 0; j < array.length - i; j++)
{
if (array[j].compareTo(array[j + 1]) > 0)
{
Comparable temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swapped = true;
}
}
}
}
感謝您的幫助或建議。
僅出於幫助,現代通用排序算法將是:
private static <T extends Comparable<? super T>> void bubbleSortObjects(T[] array)
{
int i = 0;
boolean swapped = true;
while (swapped && i < array.length - 1)
{
i++;
swapped = false;
for (int j = 0; j < array.length - i; j++)
{
if (array[j].compareTo(array[j + 1]) > 0)
{
T temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swapped = true;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.