通过EnumSet<E>
of
方法,我见过 of
的多个重载实现方法:
public static <E extends Enum<E>> EnumSet<E> of(E e)
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2)
.
.
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4, E e5)
然后是另一个带有 varargs
的重载方法
public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) {
EnumSet<E> result = noneOf(first.getDeclaringClass());
result.add(first);
for (E e : rest)
result.add(e);
return result;
}
当这个可变参数可以处理其他实现时,为什么这个方法会以这种方式重载?这有什么具体原因吗?
我浏览过同样的Javadoc,但找不到任何令人信服的解释。
最佳答案
可变参数方法创建一个数组。
public static void foo(Object... args) {
System.out.println(args.length);
}
这是可行的,因为隐式数组创建。 EnumSet
是一个设计得非常非常快的类,因此通过创建所有额外的重载,它们可以在最初的几种情况下跳过数组创建步骤。尤其如此,因为在许多情况下 Enum
没有那么多元素,如果有,EnumSet
可能不包含所有这些。
Javadoc for EnumSet<E> of(E e1, E e2, E e3, E e4, E e5)
:
Creates an enum set initially containing the specified elements. Overloadings of this method exist to initialize an enum set with one through five elements. A sixth overloading is provided that uses the varargs feature. This overloading may be used to create an enum set initially containing an arbitrary number of elements, but is likely to run slower than the overloadings that do not use varargs.
关于java - 为什么 EnumSet 有很多重载的 "of"方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924249/