gpt4 book ai didi

java - Java 9 Set.of(...) 不允许重复条目背后的推理

转载 作者:行者123 更新时间:2023-12-01 17:49:30 25 4
gpt4 key购买 nike

我刚刚遇到了由于向 java.util.Set.of(...) 添加重复条目而导致的崩溃。 Java 9 中添加的方法。

阅读该方法的文档,很明显可能会发生这样的崩溃(对我来说是耻辱),但我发现与 Set 的熟悉行为相比,这种行为是违反直觉的。以防止“在幕后”出现重复条目​​。

Set<String> set;

// set will only contain the one element "foo"
set = new HashSet<>();
set.add("foo");
set.add("foo");

// again only one element "foo"
set = new HashSet<>(Lists.of("foo", "foo"));

// crash, although it looks like a shortcut for the familiar behavior above
set = Set.of("foo", "foo");

直观上,我希望该方法在应用 Set 的“魔力”后创建一个不可变的输入参数集。

这个设计选择背后的原因是什么?

最佳答案

首先,它在文档中清楚地说明了这一点:

They reject duplicate elements at creation time. Duplicate elements passed to a static factory method result in IllegalArgumentException.

我认为这与Set.of的内部实现有关。 set.of 和 HashSet 之间的主要区别是 Set.of 为您提供了一个不可变的集合。无法添加或删除更多元素。如果您需要一个集合,它只是静态定义一个集合(我认为它更像是实用方法),我的猜测是它具有更简单的实现,没有为您删除重复项的目标。

此外,集合不必允许您添加任何元素。例如,HashSet 可能允许,但 MyCustomSet 可能不允许。来自Set接口(interface)的add方法的文档:

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 Objects.equals(e, 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.

> The stipulation above does not imply that sets must accept all elements; sets may refuse to add any particular element, including null, and throw an exception, as described in the specification for Collection.add. Individual set implementations should clearly document any restrictions on the elements that they may contain.

因此如何处理重复元素以及何时抛出异常取决于实现

关于java - Java 9 Set.of(...) 不允许重复条目背后的推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51963488/

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