寫method泛型時,遇到一個問題

※ 引述《NullLife (哀莫大於心死)》之銘言: : 但我想把Map的key跟value的型態也拿出來,就不行了... : public <ListType extends List<MapType> : ,MapType extends Map<KeyType, ValueType> : ,KeyType : ,ValueType> : void sort(ListType targetList) { : // 內容 : } : List<Map<String, String>> targetList = new ArrayList<Map<String, String>>(); : sort(targetList); : 上面這樣要塞入targetList就出現錯誤... : Bound mismatch: : The generic method sort(ListType) of type ListMapSort : is not applicable for the arguments (List<Map<String,String>>). : The inferred type Map<String,String> is not a valid substitute : for the bounded parameter <MapType extends Map<KeyType,ValueType>> : 因為我有需求在內容裡使用key的type,但一直卡住... : 想請問需要怎麼改? : 或者是我哪裡觀念有誤? : 煩請指點,感恩。 List<String> 不是 List<Object> 的 subtype,Map<String, String> 也不是 Map<Object, Object> 的 subtype。如果要仔細去看的話,應該是要閱讀 covariant/covariance,contravariant/contravariance 這一類的觀念。 我不清楚你在 sort method implementation 裡能夠以何種程度去利用到 KeyType,假設你只是希望 sort method 能夠處理任一種 key/value type 的 Map 所構成的 List,那麼你可以把 sort method declare 為: public <ListType extends List<MapType> ,MapType extends Map<? extends KeyType, ? extends ValueType> ,KeyType ,ValueType> void sort(ListType targetList) { // 內容 } 或是(你根本不需要 ValueType): public <ListType extends List<MapType> ,MapType extends Map<? extends KeyType, ?> ,KeyType> void sort(ListType targetList) { // 內容 } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.171.199.11
NullLife:感謝大大指點方向,感恩~ 11/01 09:12
public <ListType extends List<MapType> ,MapType extends Map<?, ?>> void sort(ListType targetList) { // 內容 } 上面這個method可以正常使用 List<Map<String, String>> targetList = new ArrayList<Map<String, String>>(); sort(targetList); 但我想把Map的key跟value的型態也拿出來,就不行了... public <ListType extends List<MapType> ,MapType extends Map<KeyType, ValueType> ,KeyType ,ValueType> void sort(ListType targetList) { // 內容 } List<Map<String, String>> targetList = new ArrayList<Map<String, String>>(); sort(targetList); 上面這樣要塞入targetList就出現錯誤... Bound mismatch: The generic method sort(ListType) of type ListMapSort is not applicable for the arguments (List<Map<String,String>>). The inferred type Map<String,String> is not a valid substitute for the bounded parameter <MapType extends Map<KeyType,ValueType>> 因為我有需求在內容裡使用key的type,但一直卡住... 想請問需要怎麼改? 或者是我哪裡觀念有誤? 煩請指點,感恩。

留言

這個網誌中的熱門文章

Use Case Description(描述使用案例)

列出不重複的隨機亂數

子類別建構子super觀念