我们创建一个Set为:

Set myset = new HashSet()

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


当前回答

List和Set一样只是一个接口。

HashSet是Set的一种实现,它具有添加/查找/删除性能方面的某些属性,ArrayList是List的裸实现。

如果你看了相关接口的文档,你会发现“所有已知的实现类”,你可以决定哪一个更适合你的需求。

可能是数组列表。

其他回答

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

//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());

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

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

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

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

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

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

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

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

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

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