在java9 api的集合類中,有很多看似一樣的重載of方法:
那這裏有個問題是爲什麼有了VarArgs(可變長參數)方法,還需要定義那麼多重載的方法呢?查看官方的更新日誌中可以發現有如下描述:
http://openjdk.java.net/jeps/269
These will include varargs overloads, so that there is no fixed limit on the collection size. However, the collection instances so created may be tuned for smaller sizes. Special-case APIs (fixed-argument overloads) for up to ten of elements will be provided. While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls. Significantly, the source code of the call site is the same regardless of whether a fixed-arg or varargs overload is called.
大致得意思是,雖然重載了這麼多of方法會造成api的混亂,但它避免了varargs調用引起的數組分配,初始化和垃圾收集開銷。因爲固定參數的重載方法,返回的是一個immutable list(不可變集合)。