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

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

無法使用通配符泛型為Java集合添加值

無法使用通配符泛型為Java集合添加值

素胚勾勒不出你 2019-07-12 10:54:28
無法使用通配符泛型為Java集合添加值為什么此代碼不編譯(Parent是接口)?List<? extends Parent> list = ...Parent p = factory.get();   // returns concrete implementationlist.set(0, p);    // fails here: set(int, ? extends Parent) cannot be applied to (int, Parent)
查看完整描述

3 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

它這樣做是為了安全。想象一下,如果成功的話:

List<Child> childList = new ArrayList<Child>();childList.add(new Child());List<? extends Parent> parentList = childList;
parentList.set(0, new Parent());Child child = childList.get(0); // No! It's not a child! Type safety is broken...

意義List<? extends Parent>是“是某種類型的列表,它是Parent..我們不知道哪種類型-可能是List<Parent>..List<Child>,或List<GrandChild>.“這使取任何物品都是安全的。走出.的.List<T>API和轉換自TParent,但打電話是不安全的在……里面List<T>API轉換自ParentT..因為轉換可能無效。


查看完整回答
反對 回復 2019-07-12
?
當年話下

TA貢獻1890條經驗 獲得超9個贊

List<? super Parent>

“生產者-延伸,消費者-超級”。你的List是…的消費者Parent物品。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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