List<String> supplierNames1 = new ArrayList<String>();
List<String> supplierNames2 = new LinkedList<String>();
List<String> supplierNames3 = new Vector<String>();
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"));
此外,还有许多其他库(如番石榴)提供的其他方法。
List<String> list = Lists.newArrayList("one", "two", "three");
以防万一,有人还在这个问题上徘徊。因为,我看到一两个新用户再次问同样的问题,每个人都告诉然后,不,你不能那样做,亲爱的普律当丝,除了这里给出的所有答案,我想提供额外的信息-
是的,你实际上可以这样做,List List = new List();
但是以编写接口的所有方法的实现为代价。
这个概念不是简单的List List = new List();但< / p >
List<Integer> list = new List<Integer>(){
@Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean contains(Object o) {
// TODO Auto-generated method stub
return false;
}
…等等(不能写所有的方法。)
这是匿名类的一个例子。它是正确的,当有人说,不,你不能实例化接口,,这是正确的。但你永远不能说,你不能写List List = new List();,但是,显然你可以这样做,这是一个很难做出你做不到的事的陈述。