我们创建一个Set为:

Set myset = new HashSet()

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


当前回答

用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));

其他回答

List myList = new ArrayList();

或使用泛型(Java 7或更高版本)

List<MyType> myList = new ArrayList<>();

或使用泛型(旧java版本)

List<MyType> myList = new ArrayList<MyType>();

在Java 8中

创建一个固定大小的非空列表(不支持添加、删除等操作):

List<Integer> list = Arrays.asList(1, 2); // but, list.set(...) is supported

创建一个非空的可变列表:

List<Integer> list = new ArrayList<>(Arrays.asList(3, 4));

在Java 9中

使用一个新的List.of(…)静态工厂方法:

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

List<Integer> mutableList = new ArrayList<>(List.of(3, 4));

在Java 10中

使用局部变量类型推断:

var list1 = List.of(1, 2);

var list2 = new ArrayList<>(List.of(3, 4));

var list3 = new ArrayList<String>();

并遵循最佳实践……

不要使用原始类型

从Java 5开始,泛型就成为了语言的一部分——你应该使用它们:

List<String> list = new ArrayList<>(); // Good, List of String

List list = new ArrayList(); // Bad, don't do that!

编程到接口

例如,编程到List接口:

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

而不是:

ArrayList<Double> list = new ArrayList<>(); // This is a bad idea!
List list = new ArrayList();

或者使用泛型

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

当然,你也可以用任何类型的变量替换字符串,比如Integer。

List arrList = new ArrayList();

最好按照下面的建议使用泛型:

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

arrList.add("one");

如果你使用LinkedList。

List<String> lnkList = new LinkedList<String>();

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

import com.google.common.collect.Lists;

// ...

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

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

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

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