I am trying to use HashTable (I have to use hashing) in order to store a telephone directory. I want to sort the telephone entries as they enter based on surname (alphabetically). I decided to use as a key to the HashTable the hashCode of the first character of the surname in an entry.
This is the hashCode I wrote in the Entry class:
@Override public int hashCode() { int index= getSurname().charAt(0); return index; } And this is the addEntry method which is used to add new entries to the directory:
@Override public void addEntry(Entry line) { //Throws an exception if either surname, initials or number are null. if (line.getSurname()==null||line.getInitial()==null||line.getNumber()==null){ throw new IllegalArgumentException("Please provide a Surname, Initials and a Number"); } //Throws an exception if initials are less than 2 if (line.getInitial().length() < 2) { throw new IllegalArgumentException("Please make sure that initials include both first name and surname eg: AK"); } //Throws an exception if the length of the number is not 5 characters. if (line.getNumber().length() != 5) { throw new IllegalArgumentException("Please provide a Number that is 5 characters long (make sure that it starts with 0)"); } //Throws an exception if the number doesnt start with 0. if (line.getNumber().startsWith("0") == false) { throw new IllegalArgumentException("The Number must start with a 0"); } //Initialises the key using the hashCode of surname. int key=line.getSurname().hashCode(); //If statement checks if the HashTable entries contains the key if (entries.contains(key)){ //If it does it creates a linkedList called list LinkedList<Entry> list =new LinkedList(); list=entries.get(key); ListIterator<Entry> iterator = list.listIterator(); while (iterator.hasNext()){ int x=0; String one = list.get(x).getSurname(); if (one.compareToIgnoreCase(line.getSurname()) > 0){ entries.put(x,list); x++; break; } } } else { LinkedList<Entry> list2 =new LinkedList(); list2.add(line); entries.put(key,list2); } } The problem is when I did some testing to see the results of adding different entries i found that the key (hashCode) is not generated correctly.
These are the results:
Key: -2083437938. Value: [Entry{surname='Jansas initials=KJ Phone number=05544'}] Key: -1911680082. Value: [Entry{surname='Paul initials=AP Phone number=05572'}] Key: 66344. Value: [Entry{surname='Aza initials=AZ Phone number=05212'}] Key: 867699843. Value: [Entry{surname='Penny initials=KP Phone number=05271'}] Key: 1953849949. Value: [Entry{surname='Aanais initials=AP Phone number=05562'}] Shouldnt the entry with surname "Aza" be over "Penny"and next to "Aanais"? Any ideas on how I can fix the problem?
Comparableand use a data-structure that is automatically sorted such asTreeSetor programatically sort the data usingCollections::sort. No need then to come up with a custom solution that violates the hash code contract.