Why does EnumSet have many overloaded “of” methods?

后端 未结 4 2073
[愿得一人]
[愿得一人] 2021-01-01 10:55

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

publ         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 11:09

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

提交回复
热议问题