Java9集合類中重載多個of方法原因

在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(不可變集合)。

發佈了245 篇原創文章 · 獲贊 530 · 訪問量 123萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章