List集合初始化
List集合初始化方式
- 常规方式
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("getList1: " + list);
- Arrays 工具类
// 生成的list不可变
List<String> list = Arrays.asList("1", "2", "3");
System.out.println("getList2: " + list);
// 如果要可变需要用ArrayList包装一下
List<String> numbers = new ArrayList<>(Arrays.asList("1", "2", "3"));
numbers.add("4");
System.out.println("numbers: " + numbers);
- Collections 工具类
// 生成的list不可变
List<String> list = Collections.nCopies(3, "1");
System.out.println("getList3: " + list);
// 如果要可变需要用ArrayList包装一下
List<String> dogs = new ArrayList<>(Collections.nCopies(3, "dog"));
dogs.add("dog");
System.out.println("dogs: " + dogs);
- Lists 工具类
List<String> list = Lists.newArrayList("1", "2", "3");
System.out.println("getList4: " + list);
- 匿名内部类
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
System.out.println("getList5: " + list);
- ImmutableList
List<String> list = ImmutableList.of("1", "2", "3");
System.out.println("getList6: " + list);
- Java8 Stream
List<String> list = Stream.of("1", "2", "3").collect(Collectors.toList());
System.out.println("getList7: " + list);
- Java9 List.of
List<String> list = List.of{"1", "2", "3"};
System.out.println("getList8: " + list);
Zz~