0

So this is my code for a selfadjusting linked list. its supposed to search for "item" and when it hits "item" it will transfer it to the first on the list. I tested the code and my output clearly shows that it bypasses the boolean statement on line 114 because it never holds true. Anybody can help to see what's the problem?

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 }
CHEWWWWWWWWWW
  • 169
  • 3
  • 20

1 Answers1

0

You have to override the equals method of E. Otherwise the default equals method checks the hash code. It will be false always for different objects, even if the values are same.

Assume your E is a class MyClass. you have to write like below.

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;
  }
}

I think, you didn't override equals in your class E.

Banukobhan Nagendram
  • 2,335
  • 3
  • 22
  • 27