I've been trying to implement the equals and hashCode method, so I would be able to use the remove method of arrayList.
When i execute the following
Node a = new Node(new Coord(0,0));
System.out.println(a.equals(nodes.get(0)));
System.out.println(nodes.get(0).equals(a));
System.out.println(a.hashCode() == nodes.get(0).hashCode());
System.out.println(nodes.remove(a));
I get the following output:
true
true
true
false
The question is, how can the first 3 of the output return true when the 4th returns false. The method remove should encounter nodes.get(0) and compare it to a.
These are my equals and hashCode methods:
public int hashCode() {
return coord.hashCode();
}
public boolean equals(Node node) {
return (node != null) && (this.hashCode() == node.hashCode());
}
which calls the method coord.hashCode() which is defined as:
public int hashCode() {
int hash = 23;
hash = 31 * hash + this.x;
hash = 31 * hash + this.y;
return hash;
}
Your current equals() method does not override Object.equals(), it overloads it.
Change equals() to accept an Object parameter:
public boolean equals(Object o) {
return (o instanceof Node) && (this.hashCode() == o.hashCode());
}
Java has the @Override annotation that you can put on methods so the compiler will tell you if your method does not in fact override. It's good practice to use it, so you avoid problems like this at compile time.
Note that your equals implementation has a bug: You should not compare hash codes - two "unequal" objects may (unluckily) share the same hash code.
Compare fields, not the hash code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With