Question

I have a class which is a Set and I override .equals() to check if the sets are equal element-wise. How do I override HashCode since from what I've seen there is some interdependence between the two

public class ASet{
Set g=new Set();


public boolean equals(Object s1)
{
    Set S= (Set)s1;
    for(Object o : S.getcontents())
    {
        for(Object r : g.getcontents())
        {
            if(!o.equals(r))
            {
                return false;
            }
        }
    }
    return true;
}

 public int hashCode() {
       ?????????
 }
Was it helpful?

Solution

First, let's fix your equals implementation, because it is incorrect: rather than comparing elements for equality pairwise, your code checks each element of the first set against each element of the second set. So the only case when the two sets would be considered equal under this scheme is when both sets contain exactly one element, and the elements they contain are the same.

You should make two iterators, and loop them together in a single loop. Now you can compare elements returned by the first iterator to elements returned by the second iterator, and return false if they are not the same.

Now let's do the hash code: theoretically, you could simply add up the individual hash codes of your elements, and that would be a valid implementation of hashCode():

public int hashCode() {
    int res = 0;
    for(Object r : g.getcontents()) {
        res += r.hashCode();
    }
    return res;
}

However, this is not the best hash code you could make, because two sets with different ordering would have the same hash code. A better approach is to multiply the previous value by a prime number (31 is a common example) before adding the next hash code to it, like this:

public int hashCode() {
    int res = 0;
    for(Object r : g.getcontents()) {
        res = 31 * res + r.hashCode();
    }
    return res;
}

Finally, a little note about collections and their hash codes: the main purpose of overriding hash code is so that you could use your object as a key in a hash-based collection (hash set or hash map). However, you should be extremely careful using mutable objects, such as sets and lists, as keys in maps or sets, because mutating the key that has been placed into the container already will jeopardize the structural integrity of your hash-based container.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top