How should I define a good hashCode for a circular linked list in Java?

I have set up a circular linked list data structure that represents a word, and each element in the list is a letter from the word. At the bottom of my question are the class definitions of the list and element of the list.

The purpose of the list data structure is to be able to compare cyclic words. So… “picture” and “turepic” are the same cyclic word, so the two lists will be equal.

So I override equals() when comparing two lists, and I’ve read that whenever you have to override equals(), you have to also override hashCode(). However, I don’t really have a good idea of how to do that.

How should I define a good hashCode for what I have set up? What things should I consider? In the example of the “picture” and “turepic”, the two lists are equal so their hashCode needs to be the same. Any ideas?

Thanks, Hristo

public class Letter {
 char value;
 Letter theNextNode;

 /**
  * Default constructor for an element of the list.
  * 
  * @param theCharacter - the value for this node.
  */
 Letter(char theCharacter) {
  this.value = theCharacter;
 }
}


public class CircularWord {

 /*
  * Class Variables
  */
 Letter head;
 Letter tail;
 Letter theCurrentNode;

 int iNumberOfElements;


 /**
  * Default Constructor. All characters that make up 'theWord' are stored in a 
  * circular linked list structure where the tail's NEXT is the head. 
  */
 public CircularWord(String theWord) {

  char[] theCharacters = theWord.toCharArray();

  for (int iIndex = 0; iIndex < theCharacters.length; iIndex++) {
   this.addElement(theCharacters[iIndex]);
  }

  this.theCurrentNode = head;
  this.iNumberOfElements = theCharacters.length;
 }
}

Answer

How about the sum of the hashcodes of all the elements inside your list, each multiplied by an arbitrary value?

Something like

hashCode = 1;
for (char c : myChars) {
    hashCode += 31 * c;
}

Leave a Reply

Your email address will not be published. Required fields are marked *