作者sbrhsieh (十年一梦)
看板java
标题Re: [问题] 写method泛型时,遇到一个问题
时间Thu Oct 31 21:26:58 2013
※ 引述《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
1F:推 NullLife:感谢大大指点方向,感恩~ 11/01 09:12