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/