List接口初始化
错误写法
List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));
API描述List属于一个接口,作为一个接口的话就意味着它不能被实例化,所有也就没有 new List() 一说。虽然如此,我们可以实例化已经实现了 List 接口的子类,来创建对象。
所有已知的实现类:
AbstractList, AbstractSequentialList, ArrayList, AttributeList,
CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector
下面是一些初始化 List 接口的一些方式:
List<String> list = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
ArrayList<String> list = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
JDK2
List<String> list = Arrays.asList("one", "two", "three");
JDK7
//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
JDK8
List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());
JDK9
// creates immutable lists, so you can't modify such list
List<String> immutableList = List.of("one", "two", "three");
// if we want mutable list we can copy content of immutable list
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));
Plus there are lots of other ways supplied by other libraries like Guava.
List<String> list = Lists.newArrayList("one", "two", "three");
int[] a = {1,2,3};
System.out.println(Arrays.asList(a));