Java 使用 Arrays.asList() 初始化 List 的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20538869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way of using Arrays.asList() to initialize a List
提问by Sitansu
I use this below code. Both are working fine in my application.
我使用下面的代码。两者在我的应用程序中都运行良好。
Case 1.
情况1。
List<String> coreModules =
new ArrayList<String>(Arrays.asList(
"TOOLBAR_TO_DO_LIST",
"TOOLBAR_PROPERTY",
"TOOLBAR_PEOPLE",
"TOOLBAR_INSURANCE",
"TOOLBAR_BATCH",
"TOOLBAR_INFORMATION_REFERENCE",
"TOOLBAR_LR_PROPERTY",
"TOOLBAR_CASE_FOLDER",
"TOOLBAR_INSPECTION_RESULT",
"TOOLBAR_MY_OFFICE"));
Case 2.
案例 2。
List<String> coreModules =
Arrays.asList(
"TOOLBAR_TO_DO_LIST",
"TOOLBAR_PROPERTY",
"TOOLBAR_PEOPLE",
"TOOLBAR_INSURANCE",
"TOOLBAR_BATCH",
"TOOLBAR_INFORMATION_REFERENCE",
"TOOLBAR_LR_PROPERTY",
"TOOLBAR_CASE_FOLDER",
"TOOLBAR_INSPECTION_RESULT",
"TOOLBAR_MY_OFFICE");
But I have some questions:
但我有一些问题:
- Which one is better one performance-wise?
- In which case prefer Case 2?
- 在性能方面哪一个更好?
- 在哪种情况下更喜欢案例2?
采纳答案by Lital Kolog
Case 2 is better performance-wise BUT: it returns a List with an immutable size. Meaning you cannot add/remove elements to/from it:
情况 2 在性能方面更好但是:它返回一个大小不可变的 List。这意味着您不能向其中添加/从中删除元素:
Returns a fixed-sizelist backed by the specified array. (Changes to the returned list "write through" to the array.)
返回由指定数组支持的固定大小列表。(更改返回的列表“直写”到数组。)
回答by zek_w
I think case 2 is like creating new String[10]
. You cannot change size but you can change elements. Case 1 allows you to do both.
我认为案例 2 就像创建new String[10]
. 您不能更改大小,但可以更改元素。案例 1 允许您同时执行这两项操作。
This shows what you can do with case 2: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Arrays.java#Arrays.ArrayList
这显示了您可以对案例 2 执行的操作:http: //grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Arrays.java#Arrays.ArrayList