Java Collections已经适合您的场景.调用
Collection.removeAll(Collection),它将使用equals()方法从传入集合中删除所有项目以测试相等性.
List list1 = new ArrayList();
Collections.addAll(list1, "one", "two", "three", "four");
List list2 = new ArrayList();
Collections.addAll(list2, "three", "four", "five");
list1.removeAll(list2); // now contains "one", "two"
为了使这个工作你正在存储的对象只需要正确实现equals / hashCode契约,即:给定任意两个对象a和b:
a.equals(b) == b.equals(a)
和:
a.hashCode() == b.hashCode() if a.equals(b)
定义不正确的equals和hashCode方法会产生未定义的行为,并且是集合相关问题的常见原因.