Reputation: 527
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;
}
Upvotes: 2
Views: 3059
Reputation: 425348
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.
Upvotes: 11
Reputation: 487
You can't compare equals using the method hashCode why:
a.equals(b) == true, a.hashCode() is mandatorily == b.hashCode()
a.hashCode() == b.hashCode(), a.equals(b) NOT is mandatory, more can be == false
Example of implementation using one attribute (x). Generate by eclipse:
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (x != other.x)
return false;
return true;
}
Upvotes: 1