0
votes

My assignment is supposed to be implementing certain methods from list and linkedlist, using a singly linked list (nodes).

I was wondering how would I implement the equals method and hashcode method using this, the equals method compares two lists, but I'm not sure how that translates into the nodes, does it create two lists of nodes? Or does one go after the other and how would I go about creating the method that tests for equality?


public class List12 implements java.util.List {

private Node head; private int size;

private class Node{ T data; Node next; Node previous; Node(T data){ this.data = data; } public Node(){ this.data = null; this.next = null; }

 public Node(T data, Node<T> next){
   this.data = data;
   this.next = next;
  }

 public T getData(){
   return data;
  }

 public void setData(T data){
   this.data = data;
  }

 public Node<T> getNext(){
   return next;
  }

 public void setNext(Node<T> next){
   this.next = next;
  }

}

public void removeNode(Node node){ if(size == 0) head = null; else{ if(node == head){ head = node.next; node.next.previous = null; } else{ node.next.previous = node.previous; node.previous.next = node.next; } } size--; }

public Node findNode(int index){ Node myNode; myNode = head; while( index-- > 0) myNode = myNode.next; return myNode; }

public List12() { head = null; size = 0; }

That's just the code for my nodes and its methods, I've implemented the other methods but I have no idea for the equal and hashcode method. Thanks for any help.
3

3 Answers

1
votes

Read this: It's chapter 3 from Joshua Bloch's "Effective Java". It'll tell you how to do it properly.

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

0
votes

You can use utility class EqualsBuilder from apache commons Apache EqualsBuilder. This class provides methods to build a good equals method for any class. It follows rules laid out in Effective Java by Joshua Bloch. Also, Apache commons contain HashCodeBuilder class as well.

Typical use for the code is as follows (from EqualsBuilder javadoc):

public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj.getClass() != getClass()) {
 return false;
}
MyClass rhs = (MyClass) obj;
return new EqualsBuilder()
             .appendSuper(super.equals(obj))
             .append(field1, rhs.field1)
             .append(field2, rhs.field2)
             .append(field3, rhs.field3)
             .isEquals();

}

0
votes

Don't think about object internals. You are comparing two sequences of some objects. It doesn't matter how are they implemented internally. That being said, simply compare two lists item-by-item, same story for equals. Use items, bot representation.

Please note that this implementation is so generic, that you might actually use it for any type of list or even collection.