Java 9 - List class: of() overloaded methods with varargs [duplicate]

对着背影说爱祢 提交于 2020-01-11 07:23:20

问题


In Java 9, under the List interface, there is a new method of() which according to Java documentation:

The List.of() static factory methods provide a convenient way to create immutable lists.

They have overloaded of() with up to 10 arguments together with one vararg argument. What can be the rationale behind overloading of() with 10 arguments when they have provided one vararg argument overloaded method as well?


回答1:


This is done for performance reasons.

First, empty, one element and two element lists are implemented as dedicated classes, which have no nested objects. So, constructing those is the fastest (only one allocation involved).

As for the higher "arities", the interface designers probably wanted to keep their options open to possibly implement more "fixed arity" list classes (though they had not followed this route just yet).

So indeed, the "higher arity" overloads get wrapped back into the "varargs" list constructor.

Reference: https://github.com/dmlloyd/openjdk/blob/7d7fbd09fcfd7f8cd02bf76ce10433ceeb33b3cf/jdk/src/java.base/share/classes/java/util/List.java#L788



来源:https://stackoverflow.com/questions/50224031/java-9-list-class-of-overloaded-methods-with-varargs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!