A
A
Arti-Jack2017-07-05 21:31:47
Java
Arti-Jack, 2017-07-05 21:31:47

Why does hashset add identical objects?

There is such a code.

class Point {
    int x, y;
    public Point(int x, int y) {
        super();
        this.x = x;
        this.y = y;

    }

    @Override
    public int hashCode() {
        final int prime = 31;
        return prime + prime * x + prime * prime * y;
    }

}

public class Test {
    public static void main(String[] args) {
        HashSet<Point> set = new HashSet<Point>();
        set.add(new Point(12, 13));
        set.add(new Point(9, 0));
        set.add(new Point(12, 13));
        set.add(new Point(9, 30));
        System.out.println(set.size());
    }

}

Question:
The given program will display the number ...
.
For some reason, the answer is 4, but after all, according to the idea, it should be 3, isn't it?
After all, two Point objects are exactly the same in terms of hash calculation ( return prime + prime * x + prime * prime * y;) - I'm talking about those with x and y equal to 12 and 13, respectively.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Odissey Nemo, 2017-07-07
@odissey_nemo

You need to rewrite the hashСode and equals methods together.
It so happened that equals, which is called when hasСode equality is found, is inherited from Object. And there he compares objects by their address in memory. Which, for different objects, of course, are different. That's why your HashSet thinks that ALL new objects, whatever their hashcode, will be different!
Just rewrite equals as well, so that it compares the class fields corresponding to each other in different instances. And if they are equal, HashSet will reject the second object, which has the same hashCode and the same field values.
More about these cases, for example, here .
And in general, this is a very useful and iron rule: simultaneously change (or check the performance of this sweet couple) hashCode and equals.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question