Reputation: 300
I have my object with some feilds.
public class MyObject{
private String a;
private String b;
}
I have a Set contains objects like this :
Set<MyObject> thirdSet = new HashSet<MyObject>();
Set<MyObject> firstSet=getFirstSet();
Set<MyObject> secondSet = getSecondeSet();
for (MyObjectobj : firstSet) {
if (!secondSet.contains(obj)) {
thirdSet.add(obj);
}
}
I need to select all obj that not contains in my secondSet into thridSet (obj with value not by reference) Is it possible or using collection is more better?
Upvotes: 2
Views: 263
Reputation: 1140
You'll need to override both equals and hashcode methods in your object. I'd recommend using the java 7 Objects utility methods if you can to prevent NullPointerExceptions.
@Override
public boolean equals(Object other) {
if (!(other instanceof MyObject)) {
return false;
}
MyObject that = (MyObject) other;
return Objects.equals(a, that.a) && Objects.equals(b, that.b);
}
@Override
public int hashcode() {
Objects.hash(a, b);
}
I'd also recommend taking a look at the third party library Guava if possible which would simplify your code.
Set<MyObject> thirdSet = new HashSet<>(Sets.difference(firstSet, secondSet));
Note wrapping it in a new HashSet so it can be modified (if you don't need to modify it you can remove that)
Upvotes: 2
Reputation: 29730
You should override Object#equals
and Object#hashCode
in MyObject.java.
@Override
public boolean equals(Object o) {
if (!(o instanceof MyObject)) {
return false;
}
MyObject m = (MyObject) o;
return a.equals(m.a) && b.equals(m.b);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
Also if you're allowed to use external libraries, you should check out Guava's Sets#difference
.
Upvotes: 1