You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 9 List接口of()方法重载至10个参数的设计原因探究

Why Does Java 9's List.of() Have Overloads for Up to 10 Parameters?

Great question! This is one of those under-the-hood Java design choices focused entirely on performance optimization for common use cases. Let’s break down why those overloads exist alongside the varargs version:

  • Avoid unnecessary array allocation
    When you use a varargs method (like List.of(T... elements)), the JVM automatically creates an array to wrap your parameters—even if you’re only passing 1 or 2 elements. For small lists (which are extremely common in everyday code), this array creation is unnecessary overhead. The fixed-parameter overloads (from List.of() up to List.of(T1, T2, ..., T10)) skip this array step entirely, directly constructing the immutable list from the passed arguments.

  • Optimize for high-frequency use cases
    Most of the time when developers create a small immutable list, they’re working with 1 to 10 elements. By providing dedicated overloads for these scenarios, Java’s designers eliminate the array creation cost for the most common calls. This might seem like a tiny optimization, but in applications with lots of list creation (like libraries, frameworks, or high-throughput services), the savings add up quickly.

  • Simplify internal immutable list implementation
    The fixed-parameter overloads can leverage specialized internal classes for small lists (e.g., a singleton class for 1 element, a dedicated class for 2 elements, etc.). These classes have minimal overhead compared to a generic implementation that has to handle arbitrary array inputs. The varargs version still exists for cases where you need more than 10 elements, but it’s the fallback for less common scenarios.

For example, compare these two calls:

// Uses the 2-parameter overload: no array created
List<String> smallList = List.of("a", "b");

// Uses varargs: JVM creates a String[] {"x", "y", "z", ...} under the hood
List<String> longerList = List.of("x", "y", "z", "w", "v", "u", "t", "s", "r", "q", "p");

In short, those overloads are all about making the most common uses of List.of() as efficient as possible, cutting out unnecessary object creation that would otherwise add up over time.

内容的提问来源于stack exchange,提问作者jsm24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:01:04