java - 为什么在将重复项目添加到 Set 时不会出现错误?

标签 java set

我将相同的整数两次添加到 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/

相关文章:

c++ - 根据object的成员变量查找STL::set<object>中的元素

c++ - 了解从链表中删除重复项的复杂性

java - 想要在 primefaces 中以水平方式显示错误消息

Java 的 CipherOutputStream 与 A​​pache 的 CryptoOutputStream 性能

c# - 更新对象属性 - 递减

python - 在字典键上使用 set

java,获取设置方法

java - Java Spring中的实例之间是否可以不共享静态字段?

java - 如何组合 switch 和 if else 语句

java - 如何使用java在tensorflow中训练模型