Java 关于实现可比较接口的问题
我第一次教Java编程课。我的教科书使用了Java 关于实现可比较接口的问题,java,comparable,Java,Comparable,我第一次教Java编程课。我的教科书使用了Comparable,但我在网上看到的大多数例子都使用Comparable。它们使用两个不同的接口吗 与此相关,当我在学生课堂上编写compareTo()方法时,教科书使用 public int compareTo(Object other){ if (! (other instance of Student)) throw new IllegalArgumentException("Parameter must be a Stu
Comparable
,但我在网上看到的大多数例子都使用Comparable
。它们使用两个不同的接口吗
与此相关,当我在学生课堂上编写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() );
}
如果学生类实现了可比的,那么应该使用第二种构造吗
最后,我的教科书给出了如何编写通用对象排序算法的提示。我到达以下地点。它可以工作,但会发出“未检查或不安全操作”警告。有没有办法编写一个“安全”的通用排序算法
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;
}
}
}
}
私有静态void bubbleSortObjects(可比较[]数组)
{
int i=0;
布尔交换=真;
while(交换(&i0)
{
可比温度=阵列[j];
数组[j]=数组[j+1];
阵列[j+1]=温度;
交换=真;
}
}
}
}
感谢您的帮助或建议。为了获得帮助,现代通用排序算法将是:
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;
}
}
}
}
private static将Comparable
接口参数化,并且compareTo
方法使用该类型参数。运行到泛型教程,并阅读相关内容。接口是相同的,但在Java1.5中它被赋予了通用功能。你的教科书是基于Java1.4的,这可以解释很多。这本教科书声称针对Java1.6进行了更新,但可能不是所有的教科书都得到了更新……Comparable
(没有)自2004年以来已经过时。请使用更新的教科书。