3 回答

TA貢獻1942條經驗 獲得超3個贊
如果您檢查API,List則會注意到它說:
Interface List<E>
作為一種interface手段,它無法實例化(new List()不可能)。
如果您檢查該鏈接,則會發現一些class實現的List:
所有已知的實施類:
AbstractList,AbstractSequentialList,ArrayList,AttributeList,CopyOnWriteArrayList,LinkedList,RoleList,RoleUnresolvedList,Stack,Vector
那些可以實例化。使用它們的鏈接來了解有關它們的更多信息,即IE:以了解哪個更適合您的需求。
三種最常用的可能是:
List<String> supplierNames1 = new ArrayList<String>();
List<String> supplierNames2 = new LinkedList<String>();
List<String> supplierNames3 = new Vector<String>();
獎勵:
您還可以使用,以更簡單的方式使用值實例化它Arrays class,如下所示:
List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));
但是請注意,您不允許向該列表添加更多元素fixed-size。

TA貢獻1850條經驗 獲得超11個贊
無法實例化接口,但實現很少:
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"));
另外,Guava等其他圖書館提供了許多其他方式。
List<String> list = Lists.newArrayList("one", "two", "three");

TA貢獻1856條經驗 獲得超5個贊
List是一個Interface,您不能實例化一個Interface,因為interface是一個約定,什么樣的方法應該具有您的類。為了實例化,您需要該接口的一些實現(實現)。嘗試使用下面的代碼以及非常流行的List接口實現:
List<String> supplierNames = new ArrayList<String>();
要么
List<String> supplierNames = new LinkedList<String>();
添加回答
舉報