java Java快速数组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7767431/
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
Java quick array list
提问by pleerock
I have a very simple question:
我有一个非常简单的问题:
How can I make this code more simple on Java:
如何使此代码在 Java 上更简单:
ArrayList<String> s = new ArrayList<String>();
s.add("str1");
s.add("str hello");
s.add("str bye");
//...
Something like that:
类似的东西:
ArrayList<String> s = {"a1", "str", "mystr"};
or that:
或者那个:
ArrayList<String> s = new ArrayList<String>("a1", "str", "mystr");
or that:
或者那个:
ArrayList<String> s = new ArrayList<String>();
s.addAll("a1", "str", "mystr");
or that:
或者那个:
ArrayList<String> s = new ArrayList<String>();
s.addAll(new ArrayElements("a1", "str", "mystr"));
I just want syntax hint. Thanks.
我只想要语法提示。谢谢。
回答by dty
List<String> s = Arrays.asList("a1", "str", "mystr");
List<String> s = Arrays.asList("a1", "str", "mystr");
回答by NPE
How about:
怎么样:
ArrayList<String> s = new ArrayList<String>();
Collections.addAll(s, "a1", "str", "mystr");
回答by solendil
List<String> s = Arrays.asList(new String[] {"a1", "str", "mystr"});
回答by Eng.Fouad
You can use double brace:
您可以使用双括号:
ArrayList<String> s = new ArrayList<String>()
{{
add("str1");
add("str hello");
add("str bye");
//...
}};
回答by Jon Skeet
回答by Donald Raab
Before or after Java 8 you can write:
在 Java 8 之前或之后,您可以编写:
ArrayList<String> s =
new ArrayList<>(Arrays.asList("str1", "str hello", "str bye"));
Since Java 8 you can write:
从 Java 8 开始,您可以编写:
ArrayList<String> s =
Stream.of("str1", "str hello", "str bye")
.collect(Collectors.toCollection(ArrayList::new));
With Eclipse Collectionsyou can write the following:
使用Eclipse Collections,您可以编写以下内容:
ArrayList<String> s =
Lists.mutable.with("str1", "str hello", "str bye")
.into(new ArrayList<>());
If you can use List
instead of ArrayList
:
如果您可以使用List
代替ArrayList
:
List<String> s = Lists.mutable.with("str1", "str hello", "str bye");
Note: I am a committer for Eclipse Collections.
注意:我是 Eclipse Collections 的提交者。
回答by Neeraj
If you're using Java 9, you could use List.of():
如果您使用的是 Java 9,则可以使用List.of():
List<String> s = List.of("str1", "str hello", "str bye");
But this would be an immutable list. If you need a mutable Arraylist:
但这将是一个不可变的列表。如果你需要一个可变的 Arraylist:
ArrayList<String> s = new ArrayList<>(List.of("str1", "str hello", "str bye"))