如果元素是重复的,为什么Set.of()会抛出IllegalArgumentException? [英] Why does Set.of() throw an IllegalArgumentException if the elements are duplicates?
问题描述
在Java 9中,在Set接口上引入了新的静态工厂方法,称为of(),它接受多个元素,甚至是一个元素数组。
In Java 9 new static factory methods were introduced on the Set interface, called of(), which accept multiple elements, or even an array of elements.
I想要将列表转换为集合以删除集合中的任何重复条目,这可以使用以下方式完成(在Java 9之前):
I wanted to turn a list into a set to remove any duplicate entries in the set, which can be done (prior to Java 9) using:
Set<String> set = new HashSet<>();
set.addAll(list);
但我认为使用这种新的Java 9静态工厂方法会很酷:
But I thought it would be cool to use this new Java 9 static factory method doing:
Set.of(list.toArray())
其中列表
是先前定义的字符串列表。
where the list
is a List of Strings, previously defined.
但是,当元素重复时,java抛出了 IllegalArgumentException
,也在方法的Javadoc中说明了。这是为什么?
But alas, java threw an IllegalArgumentException
when the elements were duplicates, also stated in the Javadoc of the method. Why is this?
编辑 :这个问题与另一个关于概念等效主题的问题不重复, Map.of()方法,但截然不同。并非所有()方法的静态工厂都表现相同。换句话说,当我询问Set.of()方法时,我不会点击处理Map.of()方法的问题。
Edit: this question is not a duplicate of another question about a conceptually equivalent topic, the Map.of() method, but distinctly different. Not all static factory of() methods behave the same. In other words, when I am asking something about the Set.of() method I would not click on a question dealing with the Map.of() method.
推荐答案
Set.of()
工厂方法为一个<生成不可变 Set
s strong>给定元素数量。
The Set.of()
factory methods produce immutable Set
s for a given number of elements.
在支持固定数量参数的变体中( static< E> Set< E> of()
, static< E>设置< E>(E e1)
,静态< E>设置< E>(& E e1,E e2)
等...)没有重复的要求更容易理解 - 当你调用方法时 Set.of(a,b,c )
,您声明要创建完全 3个元素的不可变 Set
,因此如果参数包含重复项,拒绝输入而不是产生较小的 Set
是有道理的。
In the variants that support a fixed number of arguments (static <E> Set<E> of()
, static <E> Set<E> of(E e1)
, static <E> Set<E> of(E e1,E e2)
, etc...) the requirement of not having duplicates are easier to understand - when you call the method Set.of(a,b,c)
, you are stating you wish to create an immutable Set
of exactly 3 elements, so if the arguments contain duplicates, it makes sense to reject your input instead of producing a smaller Set
.
而组< E - 代替; (E ...元素)
变量是不同的(如果允许创建 Set
的任意数量的元素),它遵循相同的其他变体的逻辑。如果您将 n
元素传递给该方法,则表明您希望创建的的不可变 Set
n
元素,因此不允许重复。
While the Set<E> of(E... elements)
variant is different (if allows creating a Set
of an arbitrary number of elements), it follows the same logic of the other variants. If you pass n
elements to that method, you are stating you wish to create an immutable Set
of exactly n
elements, so duplicates are not allowed.
您仍然可以创建使用以下方法从
:列表
(具有潜在重复项)中设置
You can still create a Set
from a List
(having potential duplicates) in a one-liner using:
Set<String> set = new HashSet<>(list);
在Java 9之前已经可用。
which was already available before Java 9.
这篇关于如果元素是重复的,为什么Set.of()会抛出IllegalArgumentException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!