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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:20:12  来源:igfitidea点击:

Java quick array list

javaarraysarraylist

提问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

I would use Guavaand its wonderful Listsclass:

我会使用番石榴及其精彩的Lists课程:

List<String> list = Lists.newArrayList("a1", "str", "mystr");

回答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 Listinstead 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"))