亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Java中初始化List <String>對象?

如何在Java中初始化List <String>對象?

慕婉清6462132 2019-11-05 11:15:43
我無法按照以下代碼初始化列表:List<String> supplierNames = new List<String>();supplierNames.add("sup1");supplierNames.add("sup2");supplierNames.add("sup3");System.out.println(supplierNames.get(1));我遇到以下錯誤:無法實例化類型 List<String>我該如何實例化List<String>?
查看完整描述

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。


查看完整回答
反對 回復 2019-11-05
?
慕蓋茨4494581

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");


查看完整回答
反對 回復 2019-11-05
?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

List是一個Interface,您不能實例化一個Interface,因為interface是一個約定,什么樣的方法應該具有您的類。為了實例化,您需要該接口的一些實現(實現)。嘗試使用下面的代碼以及非常流行的List接口實現:


List<String> supplierNames = new ArrayList<String>(); 

要么


List<String> supplierNames = new LinkedList<String>();


查看完整回答
反對 回復 2019-11-05
  • 3 回答
  • 0 關注
  • 1354 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號