K
K
krembrule20162019-02-07 12:36:48
Java
krembrule2016, 2019-02-07 12:36:48

Overridden equals() and hashCode(), but why does the collection still get the same elements?

Hey!
Wrote such a class. Everything is elementary.

public class CustomBox {
    private int x;
    private int z;
    public CustomBox(int x, int z){
        this.x = x;
        this.z = z;
    }
    public int getX(){return x;}
    public int getZ(){return z;}
    @Override
    public boolean equals(Object obj)
    {
        if(this.x == ((CustomBox)obj).getX() && this.x == ((CustomBox)obj).getZ())
        {
            return true;
        }
        if (obj == null || obj.getClass() != this.getClass())
        {
            return false;
        }
        return false;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        return prime + prime * this.x + prime * prime * this.z;
    }
}

But for some reason, objects with the same field values ​​still get into the HashSet collection. What to do?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan Lopatin, 2019-02-07
@krembrule2016

First, the check for class matching must be at the beginning of the equals method, otherwise an exception is possible. And secondly, you compare x twice: first with x, and then with z

D
Denis Zagaevsky, 2019-02-07
@zagayevskiy

OMFG. Actually don't do that.
Option 1) Wrote a class with fields and made the IDE generate everything else. There will be no stupid mistakes.
Option 2) I took AutoValue and everything is generated during compilation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question