对象集包含有值的对象(不是引用)(java 7)

Set of object contains by object with value (not reference) (java 7)

我有一些我的对象。

public class MyObject{

   private String a;
   private String b;

}

我有一个集合包含这样的对象:

Set<MyObject> thirdSet = new HashSet<MyObject>();

Set<MyObject> firstSet=getFirstSet();

Set<MyObject> secondSet = getSecondeSet();


for (MyObjectobj : firstSet) {
  if (!secondSet.contains(obj)) {
    thirdSet.add(obj);
  }
}

我需要select所有不包含在我的 secondSet 中的 obj 到 thridSet(值不是通过引用的 obj) 有可能还是使用集合更好?

您应该覆盖 MyObject.java 中的 Object#equalsObject#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);
}

此外,如果您被允许使用外部库,您应该查看 Guava 的 Sets#difference

您需要覆盖对象中的 equals 和 hashcode 方法。如果可以防止 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);
}

我还建议您尽可能查看第三方库 Guava,这将简化您的代码。

Set<MyObject> thirdSet = new HashSet<>(Sets.difference(firstSet, secondSet));

注意将其包装在一个新的 HashSet 中以便对其进行修改(如果您不需要修改它,可以将其删除)