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;
}