【发布时间】:2014-03-30 11:13:30
【问题描述】:
我目前正在完成一项大学作业。我有一段代码如下所示。
if(temporary > left) { }
临时变量和左变量都是“Comparable”类型。我的问题是,如何比较这两者?它们始终保存整数值,但分配迫使我将它们声明为“可比较”类型。
非常感谢任何帮助,因为我对此感到很困惑。谢谢!
【问题讨论】:
标签: java comparator comparable
我目前正在完成一项大学作业。我有一段代码如下所示。
if(temporary > left) { }
临时变量和左变量都是“Comparable”类型。我的问题是,如何比较这两者?它们始终保存整数值,但分配迫使我将它们声明为“可比较”类型。
非常感谢任何帮助,因为我对此感到很困惑。谢谢!
【问题讨论】:
标签: java comparator comparable
如果你看看http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html,你就会知道compareTo()方法是你需要的。
您可以使用temporary.compareTo(left) 并使用该值与0 进行比较。
在临时temporary.compareTo(left) 中实现compareTo(),使其返回负整数、零或正整数,因为临时小于、等于或大于左侧。
【讨论】:
compareTo(),这样如果调用对象小于作为参数传递的对象,则该方法返回负整数,如果它们相等则返回零,如果调用则返回正整数对象大于参数
在 Java 中,接口只能声明方法。 Comparable 接口声明了compareTo 方法。所以:
temporary.compareTo(left)
【讨论】:
Comparable,那么它们可以使用自己的逻辑进行比较(整数有自己的逻辑,浮点数有自己的等)。如果这些变量是您定义的自定义类型,那么您需要转到其类的定义并定义描述比较逻辑的compareTo 方法。
以下面的类为例:
public class Boot implements Comparable<Boot> {
int size;
public Boot(int size) {
this.size = size;
}
public int getSize() {
return size;
}
@Override
public int compareTo(Boot boot) {
if (boot.getSize() > size) {
return -1;
} else if (boot.size == size){
return 0;
} else {
return 1;
}
}
}
【讨论】:
我还必须使用可比较的数据类型为我的 java 类编写一个程序,它并没有真正解释什么是可比较的数据类型,但这就是我使用它对字符串数组进行插入排序的方式是实现可比较接口的对象。我的理解是,您可以使用可比较数据类型来指向一个实现可比较接口的对象,我在下面使用它来临时保存一个值。
/* 这个类实现了一个可以对数组中的字符串对象进行排序的方法。使用插入排序方法。我们的 Main 方法将调用 ObjectInsertionSorter 方法。 */
公共类可比{
public static void main(String[] Args){
/*
Create an array of strings to use as a test for the program.
*/
String[] values = {"Dylan", "Daniel", "Michael", "Amanda", "Mitsy", "Sasha", "Carlos"};
/*
Call our method and pass it the values array.
*/
objectInsertionSorter(values);
/*
Display array values.
*/
for (String element : values){
System.out.print(element + " ");
}
}
public static void objectInsertionSorter(Comparable[] array){
Comparable unsortedValue; // Temporarily holds our unsorted value
int scan; // used to scan the array;
/*
This for loop steps through our array, starting at the second value.
*/
for (int index = 1; index < array.length; index++){
unsortedValue = array[index];
scan = index;
/*
This while loop compares current value to the previous value.
If the previous value is larger, then the current value is set equal to the previous one,
and our current index "scan" is decremented.
If the previous value is smaller in comparison. Then the previous value is set equal to the unsorted value.
This will insert the unsorted value to it's correct position.
*/
while(scan > 0 && array[scan - 1].compareTo(unsortedValue) > 0){
array[scan] = array[scan - 1];
scan--;
}
// sets current value to the unsorted value
array[scan] = unsortedValue;
}
}
}
【讨论】: