java - 解释 Collections doc.oracle 中的语句

标签 java collections

http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#add(E)

在上面的链接中,它指出:

If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.

如果有人能解释最后一句话的含义,那将会有很大帮助。这是否意味着 .add() 的值即使抛出异常也会被添加到集合中?

另外,集合是否可以禁止重复并抛出异常?

最佳答案

重点是:当方法抛出异常时,它不再返回

它要么返回,要么抛出异常。因此,当您编写使用 add() 的代码时...并且该调用不会抛出给您,您就知道您添加的对象必须位于集合中。无需进一步检查 add() 返回给您的 boolean 结果值。

你看,add() 很可能返回 false(当集合恰好是一个集合,并且"new"对象已经存在时)。这取决于您实际处理的集合类型。这里的要点是:正如 javadoc 所说,该 boolean 结果仅告诉您集合本身的状态(是否发生变化,是或否)。

关于java - 解释 Collections doc.oracle 中的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40638551/

相关文章:

powershell - 从集合中删除项目的推荐方法是什么?

java - 更新记录时如何使用替换方法?

java - Java 中的集合

java - 在 REST 服务中保持身份验证启用

java - 将 ZK 与 EMF 绑定(bind)(java)

java - 如何在 SpringDM 中将 bundleContext 引用传递给 bean

Java 流 : divide into two lists by boolean predicate

Java if 语句作业

浏览器中的 Java 输出图像质量差

WPF 将两个集合合并到一个 DataGrid 中