赞
踩
本文翻译自:How to make a new List in Java
We create a Set
as: 我们创建一个Set
为:
Set myset = new HashSet()
How do we create a List
in Java? 我们如何在Java中创建List
?
参考:https://stackoom.com/question/3bLw/如何在Java中创建一个新的List
Using Google Collections , you could use the following methods in the Lists class 使用Google Collections ,您可以在Lists类中使用以下方法
- import com.google.common.collect.Lists;
-
- // ...
-
- List<String> strings = Lists.newArrayList();
-
- List<Integer> integers = Lists.newLinkedList();
There are overloads for varargs initialization and initialising from an Iterable<T>
. varargs初始化和从Iterable<T>
初始化有重载。
The advantage of these methods is that you don't need to specify the generic parameter explicitly as you would with the constructor - the compiler will infer it from the type of the variable. 这些方法的优点是您不需要像使用构造函数那样显式地指定泛型参数 - 编译器将根据变量的类型推断它。
List<Object> nameOfList = new ArrayList<Object>();
您需要导入List
和ArrayList
。
Let me summarize and add something: 让我总结并添加一些内容:
- 1. new ArrayList<String>();
- 2. Arrays.asList("A", "B", "C")
- 1. Lists.newArrayList("Mike", "John", "Lesly");
- 2. Lists.asList("A","B", new String [] {"C", "D"});
Immutable List 不变的清单
- 1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
- 2. ImmutableList.builder() // Guava
- .add("A")
- .add("B").build();
- 3. ImmutableList.of("A", "B"); // Guava
- 4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C")); // Guava
Empty immutable List 空不可变列表
- 1. Collections.emptyList();
- 2. Collections.EMPTY_LIST;
List of Characters 字符列表
- 1. Lists.charactersOf("String") // Guava
- 2. Lists.newArrayList(Splitter.fixedLength(1).split("String")) // Guava
List of Integers 整数列表
Ints.asList(1,2,3); // Guava
As an option you can use double brace initialization here: 作为选项,您可以在此处使用双括号初始化:
- List<String> list = new ArrayList<String>(){
- {
- add("a");
- add("b");
- }
- };
List arrList = new ArrayList();
Its better you use generics as suggested below: 它更好地使用泛型,如下所示:
- List<String> arrList = new ArrayList<String>();
-
- arrList.add("one");
Incase you use LinkedList. 如果你使用LinkedList。
List<String> lnkList = new LinkedList<String>();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。