为什么EnumSet有许多重载的“of”方法? [英] Why does EnumSet have many overloaded "of" methods?

查看:263
本文介绍了为什么EnumSet有许多重载的“of”方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览方法的 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.

Javadoc for EnumSet< E> (E e1,E e2,E e3,E e4,E e5)


创建一个初始包含指定元素的枚举集。此方法的重载存在用于初始化具有一到五个元素的枚举集合。提供了使用varargs功能的第六个重载。此重载可用于创建一个枚举集,最初包含任意数量的元素,但可能比不使用varargs的重载运行速度慢。

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.

这篇关于为什么EnumSet有许多重载的“of”方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆