Answer the question
In order to leave comments, you need to log in
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;
}
}
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question