我将相同的整数两次添加到 Set
,但它不会给出任何错误,尽管 Set
不允许重复。这是为什么?
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(1);
最佳答案
Set:add
不应在您尝试添加已在 Set
中的值时给您一个错误。它只会返回 false
而不会将值添加到 Set
。
检查 JavaDoc :
boolean add(E e)
Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element e to this set if the 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. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.
关于java - 为什么在将重复项目添加到 Set 时不会出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26927381/