Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

java - Why does EnumSet have many overloaded "of" methods?

While going through the EnumSet<E> of method, I have seen multiple overloaded implementations of of method:

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)

and then another overloaded method with 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;
}

When this varargs could have handled the other implementations, why this method is overloaded this way? Is there any specific reason for this?

I had gone through the Javadoc of the same, but I could not find any convincing explanation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Varargs methods create an array.

public static void foo(Object... args) {
  System.out.println(args.length);
}

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> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...