[英]Set of object contains by object with value (not reference) (java 7)
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包含这样的对象:
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? 我需要选择第二个集合中未包含的所有obj到thridSet中(值不按引用的obj)是否可能或使用collection更好?
You'll need to override both equals and hashcode methods in your object. 您需要在对象中同时覆盖equals和hashcode方法。 I'd recommend using the java 7 Objects utility methods if you can to prevent NullPointerExceptions.
如果可以防止NullPointerExceptions,建议使用Java 7 Objects实用程序方法。
@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. 我还建议尽可能查看第三方库Guava,这将简化您的代码。
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) 请注意将其包装在新的HashSet中,以便可以对其进行修改(如果不需要修改,可以将其删除)
You should override Object#equals
and Object#hashCode
in MyObject.java. 您应该在MyObject.java中重写
Object#equals
和Object#hashCode
。
@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
. 另外,如果允许使用外部库,则应查看Guava的
Sets#difference
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.