繁体   English   中英

如何比较Java中的两个“Comparable”类型变量?

[英]How to compare two "Comparable" type variables in Java?

我目前正在完成一项大学作业。 我有一段代码如下所示。

if(temporary > left) { }

临时变量和左变量都是“可比较”类型。 我的问题是,我如何比较这两者? 它们总是持有 integer 个值,但分配迫使我将它们声明为“可比较”类型。

非常感谢任何帮助,因为我对此很困惑。 谢谢!

如果您查看http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html ,您将知道compareTo()方法是您所需要的。

您可以使用temporary.compareTo(left)并使用该值与0进行比较。

在临时的temporary.compareTo(left)实现compareTo() ,使得它返回一个负整数,零或正整数,因为临时小于,等于或大于左。

在Java中,接口只能声明方法。 Comparable接口声明compareTo方法。 所以:

temporary.compareTo(left)

以下面的类为例:

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 class 编写一个程序并使用可比数据类型,它并没有真正解释可比数据类型到底是什么,但这就是我如何使用它对字符串数组进行插入排序,这些字符串是对象实现可比较的接口。 我的理解是,您可以使用可比数据类型指向实现可比接口的 object,我在下面使用它来临时保存一个值。

/* 这个class实现了一个可以对数组中的字符串对象进行排序的方法。 使用插入排序方法。 我们的 Main 方法将调用 ObjectInsertionSorter 方法。 */

公共 class 可比 {

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;
    }

}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM