Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java hashCode doubt

Tags:

java

hashcode

I have this program:

import java.util.*;
public class test {
    private String s;
    public test(String s) { this.s = s; }
    public static void main(String[] args) {
        HashSet<Object> hs = new HashSet<Object>();
        test ws1 = new test("foo");
        test ws2 = new test("foo");
        String s1 = new String("foo");
        String s2 = new String("foo");
        hs.add(ws1); 
        hs.add(ws2); 
        hs.add(s1); 
        hs.add(s2); // removing this line also gives same output.
        System.out.println(hs.size()); 
    } 
}

Note that this is not a homework. We were asked this question on our quiz earlier today. I know the answers but trying to understand why it is so.

The above program gives 3 as output.

Can anyone please explain why that is?

I think (not sure):

The java.lang.String class overrides the hashCode method from java.lang.Object. So the String objects with value "foo" will be treated as duplicates. The test class does not override the hashCode method and ends up using the java.lang.Object version and this version always returns a different hashcode for every object, so the two test objects being added are treated as different.

like image 778
moonsun Avatar asked Jul 16 '26 05:07

moonsun


2 Answers

In this case it's not about hashCode() but is about equals() method. HashSet is still Set, which has semantic of not allowing duplicates. Duplicates are checked for using equals() method which in case of String will return true

However for your test class equals() method is not defined and it will use the default implementation from Object which will return true only when both references are to the same instance.

Method hashCode() is used not to check if objects should be treated as same but as a way to distribute them in collections based on hash functions. It's absolutely possible that for two objects this method will return same value while equals() will return false.

P.S. hashCode implementation of Object doesn't guarantee uniqueness of values. It's easy to check using simple loop.

like image 126
oiavorskyi Avatar answered Jul 17 '26 17:07

oiavorskyi


Hashcode is used to narrow down the search result. When we try to insert any key in HashMap first it checks whether any other object present with same hashcode and if yes then it checks for the equals() method. If two objects are same then HashMap will not add that key instead it will replace the old value by new one.

like image 37
ankur Avatar answered Jul 17 '26 17:07

ankur