我们创建一个Set为:

Set myset = new HashSet()

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


当前回答

有很多方法可以创建Set和List。HashSet和ArrayList就是两个例子。现在在集合中使用泛型也相当普遍。我建议你看看它们是什么

这是对java内置集合的一个很好的介绍。http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html

其他回答

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

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 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 arrList = new ArrayList();

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

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

arrList.add("one");

如果你使用LinkedList。

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

有时候,你可能想要一个新的LinkedList,而不是一个新的ArrayList。从ArrayList开始,如果你有性能问题,并且有证据表明是这个列表出了问题,然后在这个列表上进行大量的添加和删除,然后-不是之前-切换到LinkedList,看看情况是否有所改善。但总的来说,还是用数组列表就好了。

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

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

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