Results 1 to 6 of 6
Like Tree1Likes
  • 1 Post By jim829

Thread: Why is hashCode() needed for checking duplicates in HashMap and Set?

  1. #1
    johnmerlino is offline Member
    Join Date
    May 2014
    Posts
    56
    Rep Power
    0

    Default Why is hashCode() needed for checking duplicates in HashMap and Set?

    The keys in a HashMap and the values in a Set must all be unique, but this can be circumvented when using custom objects in a HashMap and Set, because the compiler has no way to determine if the objects are equal or not, as shown in the example below:

    Java Code:
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    
    public class HashCodeEquals {
    
    
    	public void run(){
    		Person p1 = new Person(1, "John");
    		Person p2 = new Person(2, "Matt");
    		Person p3 = new Person(1, "John");
    		
    		Map<Person, Integer> people = new LinkedHashMap<Person, Integer>();
    		people.put(p1, 0x1);
    		people.put(p2, 0x2);
    		people.put(p3, 0x3);
    		
    		for(Person p: people.keySet()){
    			System.out.println(p);
    		}
    	}
    	
    	public static void main(String[] args) {
    		HashCodeEquals test = new HashCodeEquals();
    		test.run();
    	}
    
    	
    	public class Person {
    		private int id;
    		private String name;
    		
    		public Person(int id, String name){
    			this.id = id;
    			this.name = name;
    		}
    		
    		public String toString(){
    			return "id: " + id + " name: " + name;
    		}
    
    		private HashCodeEquals getOuterType() {
    			return HashCodeEquals.this;
    		}
    	}
    }
    This incorrectly outputs the following:

    id: 1 name: John
    id: 2 name: Matt
    id: 1 name: John

    To resolve this issue, you can override hashCode and equals, as so:

    Java Code:
    @Override
    		public int hashCode() {
    			final int prime = 31;
    			int result = 1;
    			result = prime * result + getOuterType().hashCode();
    			result = prime * result + id;
    			result = prime * result + ((name == null) ? 0 : name.hashCode());
    			return result;
    		}
    
    		@Override
    		public boolean equals(Object obj) {
    			if (this == obj)
    				return true;
    			if (obj == null)
    				return false;
    			if (getClass() != obj.getClass())
    				return false;
    			Person other = (Person) obj;
    			if (!getOuterType().equals(other.getOuterType()))
    				return false;
    			if (id != other.id)
    				return false;
    			if (name == null) {
    				if (other.name != null)
    					return false;
    			} else if (!name.equals(other.name))
    				return false;
    			return true;
    		}
    Obviously the equals method is needed because that compares the two objects. But why is the hashCode method needed?

  2. #2
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,007
    Rep Power
    6

    Default Re: Why is hashCode() needed for checking duplicates in HashMap and Set?

    You wonder why the hashCode method is needed for a HashMap and a HashSet ?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,008
    Rep Power
    20

    Default Re: Why is hashCode() needed for checking duplicates in HashMap and Set?

    Stack overflow, How does a hash table work.

    There's several explanations there, at least one of which should click with you.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,602
    Rep Power
    5

    Default Re: Why is hashCode() needed for checking duplicates in HashMap and Set?

    You seem to have a habit of not replying to folks who post comments and suggestions to your threads. This is both annoying and frustrating and is likely to reduce getting future responses.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    johnmerlino is offline Member
    Join Date
    May 2014
    Posts
    56
    Rep Power
    0

    Default Re: Why is hashCode() needed for checking duplicates in HashMap and Set?

    New to the site, wasn't sure if that was welcome or not.

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,602
    Rep Power
    5

    Default Re: Why is hashCode() needed for checking duplicates in HashMap and Set?

    First, I may have been a bit hasty when I said you wouldn't get responses. I can't really speak for others. But if I make a suggestion or question a design in a post, then I want to hear whether my advice was correct/useful or if I am misunderstanding something. Even if the poster is relatively new to Java, it can be a learning experience for both of us.

    Regards,
    Jim
    Tolls likes this.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

Similar Threads

  1. Replies: 14
    Last Post: 06-15-2014, 06:26 PM
  2. Array checking and element swapping Help Needed?
    By riches in forum New To Java
    Replies: 3
    Last Post: 03-11-2013, 01:40 PM
  3. Checking duplicates values in key field
    By drimades in forum JDBC
    Replies: 1
    Last Post: 03-12-2012, 10:59 AM
  4. Replies: 4
    Last Post: 09-15-2011, 06:39 PM
  5. [SOLVED] HashMap &amp; Spell checking
    By Dana Zra in forum New To Java
    Replies: 5
    Last Post: 10-19-2008, 09:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •