我们创建一个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>初始化有重载。

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

其他回答

一个例子:

List somelist = new ArrayList();

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

你可以在这里使用双大括号初始化:

List<String> list = new ArrayList<String>(){
  {
   add("a");
   add("b");
  }
};

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

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

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

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 8做同样的事情有更多的选择,不是更好,也不是更差,只是不同,如果你想用列表做一些额外的工作,Streams将为你提供更多的选择(过滤,映射,减少等)。

List<String> listA = Stream.of("a", "B", "C").collect(Collectors.toList());
List<Integer> listB = IntStream.range(10, 20).boxed().collect(Collectors.toList());
List<Double> listC = DoubleStream.generate(() -> { return new Random().nextDouble(); }).limit(10).boxed().collect(Collectors.toList());
LinkedList<Integer> listD = Stream.iterate(0, x -> x++).limit(10).collect(Collectors.toCollection(LinkedList::new));