【问题标题】:How to use compareTo() method to compare objects in a List?如何使用 compareTo() 方法比较 List 中的对象?
【发布时间】:2013-09-25 05:35:36
【问题描述】:

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

我的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类中的Magazines

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

【问题讨论】:

    标签: java list compare nodes


    【解决方案1】:

    一种简单的方法是让您的列表始终保持排序。

    那么,每次插入新节点时,从头部开始,使用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);
       }
    }
    

    【讨论】:

    • 感谢您的建议!我必须用这个特定的实现来完成它,但是......
    • 非常感谢!你帮了大忙:)
    【解决方案2】:

    这样

    //compares the names (Strings) of the Magazines.
    public int compareTo(Magazine mag2) {
        //assume that you have getTittle() method which returns Title
        return title.compareTo(mag2.getTitle());
    }
    

    【讨论】:

    • 这个方法与SO提到的有什么不同。
    • 不过,我想在另一个类的 add() 函数中使用 compareTo() 方法。我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 2020-03-26
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多