我们创建一个Set为:

Set myset = new HashSet()

我们如何在Java中创建一个列表?


当前回答

使用谷歌Collections,您可以在Lists类中使用以下方法

import com.google.common.collect.Lists;

// ...

List<String> strings = Lists.newArrayList();

List<Integer> integers = Lists.newLinkedList();

对于变量参数初始化和从Iterable<T>初始化有重载。

这些方法的优点是,您不需要像使用构造函数那样显式地指定泛型参数——编译器将根据变量的类型推断出它。

其他回答

//simple example creating a list form a string array

String[] myStrings = new String[] {"Elem1","Elem2","Elem3","Elem4","Elem5"};

List mylist = Arrays.asList(myStrings );

//getting an iterator object to browse list items

Iterator itr= mylist.iterator();

System.out.println("Displaying List Elements,");

while(itr.hasNext())

  System.out.println(itr.next());

使用谷歌Collections,您可以在Lists类中使用以下方法

import com.google.common.collect.Lists;

// ...

List<String> strings = Lists.newArrayList();

List<Integer> integers = Lists.newLinkedList();

对于变量参数初始化和从Iterable<T>初始化有重载。

这些方法的优点是,您不需要像使用构造函数那样显式地指定泛型参数——编译器将根据变量的类型推断出它。

因为Java 7创建泛型实例有类型推断,所以不需要在赋值的右边复制泛型参数:

List<String> list = new ArrayList<>();

固定大小的列表可以定义为:

List<String> list = Arrays.asList("foo", "bar");

对于不可变列表,你可以使用Guava库:

List<String> list = ImmutableList.of("foo", "bar");

列表可以通过多种方式创建:

1 -构造函数初始化

List是一个接口,可以通过以下方式创建List实例:

List<Integer> list=new ArrayList<Integer>();
List<Integer> llist=new LinkedList<Integer>();
List<Integer> stack=new Stack<Integer>();

2-使用Arrays.asList()

List<Integer> list=Arrays.asList(1, 2, 3);

3-使用Collections类方法

空列表

List<Integer> list = Collections.EMPTY_LIST;

OR

List<Integer> list = Collections.emptyList();

Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);

无法改变的列表

List<Integer> list = Collections
        .unmodifiableList(Arrays.asList(1, 2, 3));

单例对象列表

List<Integer> list = Collections.singletonList(2);

你可以从下面的参考链接中找到更多的方法。

参考:

https://www.geeksforgeeks.org/initializing-a-list-in-java/

在Java 9中,你可以执行以下操作来创建一个不可变的List:

List<Integer> immutableList = List.of(1, 2, 3, 4, 5);

List<Integer> mutableList = new ArrayList<>(immutableList);