Java:如何使用compareTo方法检查2个节点的顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11619056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:48:03  来源:igfitidea点击:

Java: How to use the compareTo method to check the order of 2 nodes

javalistcomparablecompareto

提问by rtrigoso

I am working on a programming assignment and I could use some help understanding the compareTo method.

我正在处理一个编程任务,我可以使用一些帮助来理解 compareTo 方法。

One of the questions of the assignment is to add an incoming element to a list. If the list is sorted, I am supposed to put the new node in its correct position. The list can be either sorted in an ascending or descending order. I thought I could check which is the order by comparing the head node to the node after (node.getNext()) but I am not sure. The line of code that I am not sure on is the following:

作业的问题之一是将传入元素添加到列表中。如果列表已排序,我应该将新节点放在正确的位置。该列表可以按升序或降序排序。我以为我可以通过将头节点与 (node.getNext()) 之后的节点进行比较来检查哪个是顺序,但我不确定。我不确定的代码行如下:

if(head.getContent().compareTo(tp.getContent())==1)

head is the first node is a generic data type T, which has already been added. tp is head.getNext() just to save space and is also a generic data type T, since I am sure I will be typing it again. I did not write a compareTo method on the program because the professor told me that simply call the compareTo method to compare another generic data type. Also, I am not sure on the difference between:

head 是第一个节点,是泛型数据类型 T,已添加。 tp 是 head.getNext() 只是为了节省空间,也是通用数据类型 T,因为我确定我会再次输入它。我没有在程序上写 compareTo 方法,因为教授告诉我只需调用 compareTo 方法来比较另一种通用数据类型。另外,我不确定以下之间的区别:

extends Comparable<T>

and

implements Comparable<T>

but the assignment requires me to use the first one.

但作业要求我使用第一个。

if the head node element is 1 and the next on is 3, what will the output of the if statement be? true or false?

如果头节点元素是 1,下一个元素是 3,那么 if 语句的输出是什么?对或错?

回答by Affe

Basically the way to think of compareTo is to ALWAYSput a zero on the other side of it and then imagine that the operator is between the two arguments.

基本上,考虑 compareTo 的方法是始终在它的另一侧放一个零,然后想象运算符位于两个参数之间。

A.compareTo(B) == 0; // A == B
A.compareTo(B) > 0; // A > B
A.compareTo(B) >= 0; // A >= B

//etc etc etc

This makes it much easier to read and saves you trying to figure out what you actually meant by >-1or something in two years

这使阅读变得更加容易,并节省了您>-1在两年内试图弄清楚您的实际含义或某些事情的时间

回答by ???v?т?

To answer the second part of your question, Comparable<T>is an interface that defines a single method: compareTo().

要回答问题的第二部分,Comparable<T>是一个定义单个方法的接口:compareTo().

  • Use extends Comparable<T>to create a sub-interface that adds more methods to Comparable.

  • Use implements Comparable<T>for a concrete classthat implements the interface.

  • 使用extends Comparable<T>创建子接口上增加了更多的方法来比较的。

  • 使用implements Comparable<T>的具体实现接口。

If the professor wants you to use extends Comparablethen perhaps he wants you to create an interface for your nodes, something like this:

如果教授希望您使用,extends Comparable那么他可能希望您为您的节点创建一个界面,如下所示:

public interface Node<T> extends Comparable<Node<?>> {

    T getContent();
}

回答by Kumar Vivek Mitra

1.Use java.lang.Comparableinterface.

1.使用java.lang.Comparable界面

public interface Comparable<T>{
    public int compareTo(){
    }
}

2.Your class needs to implement Comparable, and then each element will be callingcompareTo()on each otherto sort themselves.

2.你的类需要实现可比,然后每个元素将调用compareTo()对方自己解决。

3.If you want to sort in more than one way..then usejava.util.Comparator, which use compare()method

3.如果你想以多种方式排序..然后使用java.util.Comparator,哪个使用compare()方法

回答by CosmicComputer

The Comparable interface simply says that you must have a way of comparing two objects A and B, both of type T, and that, as Affe notes, you should return 1 if A > B, 0 if A and B are equal, and -1 if A < B. Note that equal does not mean == as in Java == means "do these two object references refer to the same thing", not "are these two objects essentially the same."

Comparable 接口只是说你必须有一种方法来比较两个对象 A 和 B,都是 T 类型,而且,正如 Affe 指出的,如果 A > B,你应该返回 1,如果 A 和 B 相等,则返回 0,并且 - 1 if A < B。请注意,equal 并不意味着 ==,因为在 Java 中 == 意味着“这两个对象引用是否指向同一事物”,而不是“这两个对象本质上是否相同”。

It does not, however, define how you must compare them; whichever class implements it must do so. You can say that A is greater than B based on the value of some field in type T, or you can do something more complex. Since a lower integer value, for example, indicates a higher priority (1 < 2, but a priority one issue is higher-up than a priority two issue), the basis of comparison is not always apparent, but in your case, if you have a series of nodes whose contents are integers, it would make sense to say compare two nodes as you would their integer values; e.g. if the integer value stored in A is greater than the integer value stored in B, A > B so A.compareTo(B) returns 1.

但是,它没有定义您必须如何比较它们;无论哪个类实现它都必须这样做。您可以根据类型 T 中某个字段的值说 A 大于 B,或者您可以做一些更复杂的事情。例如,由于较低的整数值表示较高的优先级(1 < 2,但优先级一问题高于优先级二问题),因此比较的基础并不总是很明显,但在您的情况下,如果您有一系列内容为整数的节点,可以说比较两个节点就像比较它们的整数值一样;例如,如果存储在 A 中的整数值大于存储在 B 中的整数值,则 A > B 所以 A.compareTo(B) 返回 1。

As for the direction to use extends rather than implements - well, when you are using generic types (such as T), you use extends rather than implements. When you are defining a class, implements means that you are using the method headers of an interface, and when you are defining an interface, extends means that you are using the interface as a superinterface, much like a superclass to a class. So if you say that Class A implements Comparable, you are saying that A must have a method to compare itself to classes which implement Comparable.

至于使用extends而不是implements的方向——好吧,当你使用泛型类型(比如T)时,你使用extends而不是implements。当你定义一个类时,implements 意味着你正在使用一个接口的方法头,而当你定义一个接口时,extends 意味着你将接口用作超接口,就像类的超类一样。因此,如果您说 Class A 实现了 Comparable,那么您是在说 A 必须有一种方法来将自己与实现 Comparable 的类进行比较。

回答by Pradeep Yadava

public class UseComparetoMethod{

    static String arr[] = {"Ram", "Bharat", "Laxman", "Satrughna"};

    public static void main(String ar[]) {

        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j].compareTo(arr[i]) < 0) {
                    String t = arr[i];
                    arr[i] = arr[j];
                    arr[j] = t;
                }
            }
            System.out.println(arr[i]);
        }
    }
}

A completer description here

更完整的描述在这里

回答by Pradeep Yadava

package example;

包示例;

import java.util.*;

导入 java.util.*;

/** * * @author pradeep */ public class ComparableDemo {

/** * * @author pradeep */ 公共类 ComparableDemo {

public static void main(String args[]) {
    User u = new User();
    u.setName("pradeep");
    User u1 = new User();
    u1.setName("Ajeet");
    User u2 = new User();
    u2.setName("sameer");
    List<User> list = new ArrayList<User>();
    list.add(u);
    list.add(u1);
    list.add(u2);
    Collections.sort(list);
    for (User user : list) {
        System.out.println(user.getName());
    }
}

}

}

class User implements Comparable {

类用户实现 Comparable {

private String name;

/**
 * @return the name
 */
public String getName() {
    return name;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
    this.name = name;
}

@Override
public int compareTo(User n) {
    if (this.getName().compareTo(n.getName()) > 0) {
        return 1;
    }
    if (this.getName().compareTo(n.getName()) < 0) {
        return -1;
    }
    return 0;
}

}you can learn more about java here!!

}您可以了解更多关于Java在这里!

回答by digitaljoel

You should look at the documentation for the comparableinterface which defines the compareTo method. Then you will know what the return value means in terms of the sorting order of your list.

您应该查看定义 compareTo 方法的可比较接口的文档。然后,您将了解返回值在列表排序方面的含义。

Comparable is an interface. An interface can extend another interface. A class can implement an interface.

Comparable 是一个接口。一个接口可以扩展另一个接口。一个类可以实现一个接口。