java - 如何使用compareTo()方法比较List中的对象?

标签 java list compare nodes

我有一个名为 ListNode 的类,它的工作方式类似于列表。我想使用这个类建立杂志对象的列表。在我的 MagazineList 类中,我想编辑 add 方法,这样当我插入 Magazine 时,它们将按字母顺序排序。我怎样才能做到这一点?

我的ListNode类:

    public class ListNode {
      private Object value;
      private ListNode next;

      //intializes node
      public ListNode (Object initValue, ListNode initNext) {
       value = initValue;
       next = initNext;
      }

    //returns value of node
    public Object getValue () {
      return value;
    }

     //returns next reference of node
    public ListNode getNext () {
       return next;
    }

     //sets value of node
    public void setValue (Object theNewValue) {
      value = theNewValue;
    }

    //sets next reference of node
    public void setNext (ListNode theNewNext) {
       next = theNewNext;
    }
   }

我的MagazineList类的add方法:

    //when instantiated, MagazineList's  list variable is set to null
    public void add (Magazine mag) {

      ListNode node = new ListNode (mag, null);
      ListNode current;

      if (list == null)
         list = node;
      else {
         current = list;
         while (current.getNext() != null)
            current = current.getNext();
         current.setNext(node);
      }
   }

我用这个方法来比较Magazine类中的Magazine:

 //compares the names (Strings) of the Magazines.
  public int compareTo(Magazine mag2) {
     return (title).compareTo(mag2.toString());
  }

最佳答案

实现此目的的一个简单方法是始终保持列表有序。

然后,每次插入新节点时,从头部开始,使用 compareTo 方法将新节点与列表中的每个节点进行比较,并将新节点插入到该节点之后compareTo 返回正值。

一个基本的实现可能是这样的。不过,您需要改进它并考虑边缘情况等。

//when instantiated, MagazineList's  list variable is set to null
public void add (Magazine mag) {

   ListNode node = new ListNode (mag, null);
   ListNode current;

   if (list == null)
     list = node;
   else {
    current = list; // you list head
    while (node.compareTo(current) < 0)
       current = current.getNext();
   ListNode next = current.getNext();
   current.setNext(node);
   node.setNext(next);
   }
}

关于java - 如何使用compareTo()方法比较List中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18997004/

相关文章:

javascript - 为什么检查三个字符串之间的相等性不起作用,但检查三个数字之间的相等性呢?

haskell - 如何在 Haskell 中检查一个字符串是否小于另一个字符串?

java - 如何为 Java 和 jQuery i18n 共享相同的属性文件

list - 在 OCaml 中将整数列表转换为字符串

java - JTextField 字符串不起作用

c# - linq查询中的自动编号

python - 如何从Python中的循环创建可变矩阵列表?

Java - 仅比较特定键的两个 Maps 条目

java - 如何打印出正确的输出

java - vim java 全能