gpt4 book ai didi

java - Collections doc.oracle 中的说明语句

转载 作者:行者123 更新时间:2023-11-30 07:58:14 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com