简体   繁体   中英

Method signature with generic map extends object

Although this Piece of code is working, it still grinds my gears:

public static <K, V> Map<K, V> entityListToIdMap(List<? extends BaseEntity<K>> list, Class<K> keyClass) {
    Map<K, V> map = new TreeMap<K, V>();
    if(list != null){
        for (BaseEntity<K> item : list) {
            map.put(item.getId(), (V) item);
        }
    }
    return map;
}

What i'm missing is, to tell the method signature, that V extends BaseEntity<K>. This may also lead to the unchecked warning which makes it necessary to cast the item in the value to V .

How can I tell V that it must extend BaseEntity<K>?

based on accepted answer from @Ori Lentz, the complete solution:

public static <K, V extends BaseEntity<K>> Map<K, V> entityListToIdMap(List<V> list, Class<K> keyClass) {
    Map<K, V> map = new TreeMap<K, V>();
    if (list != null) {
        for (V item : list) {
            map.put(item.getId(), item);
        }
    }
    return map;
}

定义通用类型时,只需定义它:

public static <K, V extends BaseEntity<K>> Map<K, V> entityListToIdMap(..) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM