0

所以这是我的自调整链表代码。它应该搜索“项目”,当它点击“项目”时,它将把它转移到列表中的第一个。我测试了代码,我的输出清楚地表明它绕过了第 114 行的布尔语句,因为它永远不会成立。任何人都可以帮助看看是什么问题?

100     // Return the number of probes to search item in list.
101     public int search(E item) {
102 
103         int totalProbes = 0;
104 
105         if(numNodes == 0)   {
106             System.out.println(totalProbes);
107             return totalProbes;
108         }
109         else if(this.contains(item))    {
110             System.out.println(item);
111             ListNode<E> previous = null;
112             ListNode<E> current = head;
113             while(current != null)  {
114                 if(current.equals(item))    {
115                     previous.setNext(current.getNext());
116                     current.setNext(head);
117                     head = current;
118                     totalProbes++;
119                     System.out.println("FOUND" + totalProbes);
120                     break;
121                 }
122                 previous = current;
123                 current = current.getNext();
124                 totalProbes++;
125                 System.out.println(totalProbes);
126             }
127             System.out.println(totalProbes);
128             return totalProbes;
129         }
130         else
131             System.out.println(totalProbes);
132         return totalProbes;
133     }
134 }
4

1 回答 1

0

您必须覆盖 E 的 equals 方法。否则默认的 equals 方法会检查哈希码。对于不同的对象,即使值相同,它也总是错误的。

假设您的 E 是 MyClass 类。你必须像下面这样写。

public class MyClass{
  private int val1;
  private int val2;

  @Override
  public boolean equals(Object other){
    if (other == null) return false;
    if (other == this) return true;
    if (!(other instanceof MyClass))return false;
    MyClass otherMyClass = (MyClass)other;
    if(otherMyClass.val1 == this.val1 && otherMyClass.val2 == this.val2)
         return true;
    else
         return false;
  }
}

我认为,您没有在 E 类中覆盖 equals 。

于 2014-03-13T07:03:51.490 回答