问题描述
在浏览方法的 EnumSet< E>
时,我看到了多个重载的实现
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;
}
当这个varargs可以处理其他实现时,为什么这个方法是重载的办法?这有什么特别的原因吗?
When this varargs could have handled the other implementations, why this method is overloaded this way? Is there any specific reason for this?
我已经浏览了Javadoc,但我找不到任何令人信服的解释。
I had gone through the Javadoc of the same, but I could not find any convincing explanation.
推荐答案
Varargs方法创建一个数组。
Varargs methods create an array.
public static void foo(Object... args) {
System.out.println(args.length);
}
这样做是因为隐式数组创建。 EnumSet
是一个设计非常,非常快的类,所以通过创建所有额外的重载,他们可以在前几个步骤中跳过数组创建步骤病例。这是特别真实的,因为在许多情况下 Enum
没有那么多的元素,如果它们, EnumSet
可能不包含所有这些。
This works, because of the implicit array creation. EnumSet
is a class designed to be very, very fast, so by creating all the extra overloads they can skip the array creation step in the first few cases. This is especially true since in many cases Enum
don't have that many elements, and if they do, the EnumSet
might not contain all of them.
:
这篇关于为什么EnumSet有许多重载的“of”方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!