If I take for example a HashSet<E>
, and add objects to it, how does it check if the object's already there?
I have the following simple setup:
private class MyObject {
String text;
public MyObject(String text) {
this.text = text;
}
@Override
public boolean equals(Object o) {
if (o != null && o instanceof MyObject) {
return ((MyObject) o).text.equals(text);
}
return false;
}
}
In my project I have many objects like this, but all initialized separately. I want to filter the doubles, by adding all to a Set
, like this:
MyObject m1 = new MyObject("1");
MyObject m2 = new MyObject("1");
MyObject m3 = new MyObject("2");
System.out.println(m1.equals(m2)); //expected: true, result: true
System.out.println(m1.equals(m3)); //expected: false, result: false
Set<MyObject> myObjects = new HashSet<MyObject>();
myObjects.add(m1);
myObjects.add(m2);
myObjects.add(m3);
System.out.println(myObjects.size()); //expected: 2, result: 3
Set<String> stringList = new HashSet<String>();
stringList.add("1");
stringList.add("1");
stringList.add("2");
System.out.println(stringList.size()); //expected: 2, result: 2
How can I make it so that my myObjects
set does not contain these doubles? So m1
and m2
are different instances, but have the same content so I only need m1
.
Edit
Based on Mathias Schwarz's answer I've implemented the hashCode()
function as follows:
@Override
public int hashCode() {
return text.hashCode();
}
But how would I implement this method if I have a more complex class with multiple fields?