我们创建一个Set为:
Set myset = new HashSet()
我们如何在Java中创建一个列表?
我们创建一个Set为:
Set myset = new HashSet()
我们如何在Java中创建一个列表?
当前回答
让我总结一下并补充一下:
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 9中,你可以执行以下操作来创建一个不可变的List:
List<Integer> immutableList = List.of(1, 2, 3, 4, 5);
List<Integer> mutableList = new ArrayList<>(immutableList);
List list = new ArrayList();
或者使用泛型
List<String> list = new ArrayList<String>();
当然,你也可以用任何类型的变量替换字符串,比如Integer。
因为Java 7创建泛型实例有类型推断,所以不需要在赋值的右边复制泛型参数:
List<String> list = new ArrayList<>();
固定大小的列表可以定义为:
List<String> list = Arrays.asList("foo", "bar");
对于不可变列表,你可以使用Guava库:
List<String> list = ImmutableList.of("foo", "bar");
用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.lang.UnsupportedOperationException。
List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});
List<String> fixedSizeList = Arrays.asList("Male", "Female");
List<String> fixedSizeList = List.of("Male", "Female"); //from java9
以下版本是一个简单的列表,您可以在其中添加/删除任意数量的元素。 List<String> List = new ArrayList<>();
这是如何在java中创建一个LinkedList,如果你需要频繁地插入/删除列表上的元素,你应该使用LinkedList而不是ArrayList List<String> linkedList = new linkedList <>();