当前位置:   article > 正文

如何在Java中创建一个新的List_java new list string

java new list string

本文翻译自: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


#1楼

参考:https://stackoom.com/question/3bLw/如何在Java中创建一个新的List


#2楼

Using Google Collections , you could use the following methods in the Lists class 使用Google Collections ,您可以在Lists类中使用以下方法

  1. import com.google.common.collect.Lists;
  2. // ...
  3. List<String> strings = Lists.newArrayList();
  4. 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. 这些方法的优点是您不需要像使用构造函数那样显式地指定泛型参数 - 编译器将根据变量的类型推断它。


#3楼

List<Object> nameOfList = new ArrayList<Object>();

您需要导入ListArrayList


#4楼

Let me summarize and add something: 让我总结并添加一些内容:

JDK JDK

  1. 1. new ArrayList<String>();
  2. 2. Arrays.asList("A", "B", "C")

Guava 番石榴

  1. 1. Lists.newArrayList("Mike", "John", "Lesly");
  2. 2. Lists.asList("A","B", new String [] {"C", "D"});

Immutable List 不变的清单

  1. 1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
  2. 2. ImmutableList.builder() // Guava
  3. .add("A")
  4. .add("B").build();
  5. 3. ImmutableList.of("A", "B"); // Guava
  6. 4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C")); // Guava

Empty immutable List 空不可变列表

  1. 1. Collections.emptyList();
  2. 2. Collections.EMPTY_LIST;

List of Characters 字符列表

  1. 1. Lists.charactersOf("String") // Guava
  2. 2. Lists.newArrayList(Splitter.fixedLength(1).split("String")) // Guava

List of Integers 整数列表

Ints.asList(1,2,3);                                             // Guava

#5楼

As an option you can use double brace initialization here: 作为选项,您可以在此处使用双括号初始化:

  1. List<String> list = new ArrayList<String>(){
  2. {
  3. add("a");
  4. add("b");
  5. }
  6. };

#6楼

List arrList = new ArrayList();

Its better you use generics as suggested below: 它更好地使用泛型,如下所示:

  1. List<String> arrList = new ArrayList<String>();
  2. arrList.add("one");

Incase you use LinkedList. 如果你使用LinkedList。

List<String> lnkList = new LinkedList<String>();
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/77358
推荐阅读
相关标签
  

闽ICP备14008679号