简体   繁体   English

使用 Comparable 接口对通用链表进行排序

[英]Use Comparable Interface to Sort a Generic Linked List

I want to sort my self implemented Linked List Using Comparable Interface with Java .I need to implement the compareTo method : Here is the code for my class ListElement :我想使用 Java 的 Comparable Interface 对我自己实现的链表进行排序。我需要实现 compareTo 方法:这是我的类 ListElement 的代码:

 public class ListElement implements Comparable<ListElement> {
    public Object wert;
    public ListElement nachFolger;

    public ListElement(Object wert , ListElement nachFolger) {
        this.wert=wert;
        this.nachFolger=nachFolger;
    }

    @Override
    public int compareTo(ListElement a) {
        if(this.nachFolger.wert - a.wert) {
            return 1;
        }
        return 0;
    }
}

But I get an error , any recommendations ?但是我收到一个错误,有什么建议吗?

You are trying to subtract to references of type Object .您正在尝试减去Object类型的引用。

Your element type should implement Comparable :您的元素类型应该实现Comparable

public class ListElement<T extends Comparable<T>> implements Comparable<ListElement<T>> {
    public T wert;
    public ListElement<T> nachFolger;

    public ListElement(T wert, ListElement<T> nachFolger) {
        this.wert=wert;
        this.nachFolger=nachFolger;
    }

    @Override
    public int compareTo(ListElement<T> a) {
        return wert.compareTo(a.wert);
    }
}

In Java, subtract operation only applies to numeric literals (and auto-unboxed numeric objects).在 Java 中,减法运算仅适用于数字文字(和自动拆箱的数字对象)。 As you are trying to use it on non numeric Object type, you are getting the error.当您尝试在非数字Object类型上使用它时,您会收到错误消息。 If you want to compare two wert values, you can do the following:如果要比较两个wert值,可以执行以下操作:

  • Change the type to number from Object so that you can compare, eg:将类型从Object更改为number以便您可以进行比较,例如:

     public Object wert; @Override public int compareTo(ListElement a) { return wert.compareTo(a.wert); }
  • Change the type to Comparable so you can use compareTo on two wert objects将类型更改为Comparable以便您可以在两个wert对象上使用compareTo

     public Comparable wert; @Override public int compareTo(ListElement a) { return wert.compareTo(a.wert); }

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

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