为什么Guava的ImmutableList有这么多重载的()方法? [英] Why does Guava's ImmutableList have so many overloaded of() methods?
问题描述
我只是看着Guava的 ImmutableList
我注意到()方法的重载了12次。
I was just looking at Guava's ImmutableList
and I noticed that the of()
method was overloaded 12 times.
在我看来他们所需要的只是:
It looks to me that all they needed was:
static <E> ImmutableList<E> of();
static <E> ImmutableList<E> of(E element); // not even necessary
static <E> ImmutableList<E> of(E... elements);
有这么多类似变化的原因是什么?
What's the reason for having so many similar variations?
推荐答案
Varargs和泛型不能很好地融合在一起。 Varargs方法可能会导致带有泛型参数的警告,并且重载会阻止该警告,除非在极少数情况下您希望使用 of()
。
Varargs and generics do not play nicely together. Varargs methods can cause a warning with generic arguments, and the overloads prevent that warning except in the rare case that you want to add more than 11 items to the immutable list using of()
.
来源中的评论说:
这些是十一。在那之后,你只需要获得varargs表格,以及随之而来的任何警告。 :(
These go up to eleven. After that, you just get the varargs form, and whatever warnings might come along with it. :(
请注意Java 7的 @ SafeVarargs 注释专门添加,以消除对此类事物的需求。单个(E ... )
可以使用带有 @SafeVarargs
注释的方法,并且不会给出带有通用参数的警告。
Note that Java 7's @SafeVarargs annotation was added specifically to eliminate the need for this sort of thing. A single of(E...)
method annotated with @SafeVarargs
could be used and would not give warnings with generic arguments.
这篇关于为什么Guava的ImmutableList有这么多重载的()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!