java 8中初始化list的方法有以下几种:
// 1 new ArrayList,依次添加元素,这种方式最常见,只是代码不够简洁 List<Object> one = new ArrayList<>(); one.add("1"); one.add("2"); System.out.println(one); // 2 Arrays.asList,一句话就能初始化,简洁。但是这种方式初始化的list是不可改变的,无法添加和删除 List<Object> two = Arrays.asList("a","b","c"); // two.add("d"); // 如果想要可变,使用new ArrayList包装一下 two = new ArrayList<>(Arrays.asList("aa","bb","cc")); two.add("dddd"); System.out.println(two); // 3 {{}},匿名内部类的方式,这种方式降低了代码可读性,而且存在内存泄露的风险 List<Object> three = new ArrayList<Object>(){{ add("ni"); add("wo"); add("ta"); }}; three.add("women"); System.out.println(three); // 4 stream,未免大材小用 List<Object> four = Stream.of("ff","gg").collect(Collectors.toList()); four.add("kk"); System.out.println(four);
// 1 new ArrayList,依次添加元素,这种方式最常见,只是代码不够简洁
List<Object> one = new ArrayList<>();
one.add("1");
one.add("2");
System.out.println(one);
// 2 Arrays.asList,一句话就能初始化,简洁。但是这种方式初始化的list是不可改变的,无法添加和删除
List<Object> two = Arrays.asList("a","b","c");
// two.add("d");
// 如果想要可变,使用new ArrayList包装一下
two = new ArrayList<>(Arrays.asList("aa","bb","cc"));
two.add("dddd");
System.out.println(two);
// 3 {{}},匿名内部类的方式
List<Object> three = new ArrayList<Object>(){{
add("ni");
add("wo");
add("ta");
}};
three.add("women");
System.out.println(three);
// 4 stream,未免大材小用
List<Object> four = Stream.of("ff","gg").collect(Collectors.toList());
four.add("kk");
System.out.println(four);