我们创建一个Set为:

Set myset = new HashSet()

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


当前回答

一个例子:

List somelist = new ArrayList();

您可以查看javadoc for List,并找到包含在java api中的List接口的所有已知实现类。

其他回答

让我总结一下并补充一下:

JDK

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"});

不可变列表

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

空不可变列表

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

字符列表

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

整数列表

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

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

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

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

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

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

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

就像java中数组列表的声明一样

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable  

有许多方法可以在java中创建和初始化数组列表。

 1) List list = new ArrayList();

 2) List<type> myList = new ArrayList<>();

 3) List<type> myList = new ArrayList<type>();

 4) Using Utility class

    List<Integer> list = Arrays.asList(8, 4);
    Collections.unmodifiableList(Arrays.asList("a", "b", "c"));

 5) Using static factory method

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


 6) Creation and initializing at a time

    List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});



 Again you can create different types of list. All has their own characteristics

 List a = new ArrayList();
 List b = new LinkedList();
 List c = new Vector(); 
 List d = new Stack(); 
 List e = new CopyOnWriteArrayList();

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

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

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

此外,如果你想创建一个列表,其中有东西(尽管它将是固定大小):

List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");