Lets say I have a class
public class Data{
public int k;
public int l;
public Data(int k, int l){
this.k = k;
this.l = l;
}
The answer from Makoto is right. The same i would say to. But you have some mistakes in your code above.
To your question: Makoto's answer is one solution. My solution is to use the help of eclipse to auto generate hashcode and equals methods. Like this:
public class Data {
// your class code here
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + k;
result = prime * result + l;
return result;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Data)) {
return false;
}
Data other = (Data) obj;
if (k != other.k) {
return false;
}
if (l != other.l) {
return false;
}
return true;
}
}
By convention you want to override hashcode also when you override equals
You will most probably find that the indexOf uses the hashcode method to match the object not the equals
If you use eclise to edit you code - eclipse will generate a good equals and hashcode method for you from the "source" menu.
The signature of your equals
method is wrong. You are not overriding the equals
in Object
, but just overloading it.
To override the behavior of equals
method in Object
, your signature must exactly match with the one in Object
. Try this:
public boolean equals(Object o) {
if(!(o instanceof Data)) return false;
Data other = (Data) o;
return (this.k == other.k && this.l == other.l);
}
In addition, as others suggested, it is a good idea to override hashCode
method also for your object to work correctly in map based collections.
The indexOf()
method does go through the entire list. Here's an excerpt from Java 7 source code:
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
It'd be better to let Java go through it than write it yourself. Just make sure that your equals
method is sufficient at finding the object you want. You'll also want to override hashCode()
as well.
I won't write your equals
method out, but I would recommend that you at least:
if(boolean_expr) { return true; }
; just return the boolean expression.equals
method - the signature of that requires an Object
parameter, not Date
.