I have: - MyClass with hashCode() overwritten - I'll try to avoid adding a second instance of MyClass with the same content to an List using the contains() method of the List.
How can I achive this ? I thought this is done by just overriding the hashCode() method ?
I guess code says more then words
public class TestClass {
public static void main(String[] args){
MyClass myclass1 = new MyClass(2);
MyClass myclass2 = new MyClass(2);
List<MyClass> myclasses = new ArrayList<MyClass>();
myclasses.add(myclass1);
if(!myclasses.contains(myclass2)){
myclasses.add(myclass2);
System.out.println("I'll add ...");
}
System.out.println(myclasses.size());
}
}
public class MyClass {
int id = -1;
String something = "";
public MyClass(int idparam){
this.id = idparam;
}
@Override
public int hashCode() {
return id;
}
}
Updated Class:
public boolean equals(MyClass secondmyclass) {
return secondmyclass.id == this.id;
}
You have to override equals and hashcode methods. The object is not contained in the list as is not equal to any instance in the list, even if it generates same hash code.
@Override
public boolean equals(Object obj) {
boolean eq = false;
if (obj != null && obj instanceof YOURCLASS) {
eq = this.getId().equals((YOUCLASS)obj.getId());
}
}
Equals method should look like this. YOURCLASS is the name of the bean added to the list. You have to compare the key fields after verifying the obj instance is not null and is of the same type of the original instance.
In your example YOURCLASS is MyClass and the comparison inside equals should be with == instead of equals, as you are not using int insteand of Integer for the field.