我有一个类如下(Bean):
class KeysHolder {
Long kitId;
String packId;
String boxId;
// getters and setters
.......
// @Override equals and hashCode
}
我有一个包含上述对象的集合
Set<KeysHolder> keys;
现在,如果我继续将对象添加到集合中,它是否会根据每个元素的值自动删除重复项? (我知道它在内部使用了 Overridden equals 和 hashCode 方法)。
最终集合不应包含基于每个字段相等性的任何重复项。
obja.kitId = objb.kitId
objb.packid = objb.packId
obja.boxId = objb.boxId
谢谢!
最佳答案
Now if I keep adding the object to the set, does it automatically remove duplicates based on the values of the each elements.
如果Set
实现发现该元素重复,则根本不会插入。
来自 HashSet#add(E e) 的 Javadocs :
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
关于java - 使用 Set - 自动删除重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17222226/