gantners
gantners

Reputation: 471

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;
}

Upvotes: 1

Views: 620

Answers (1)

Ori Lentz
Ori Lentz

Reputation: 3688

Simply define it when you define the generic type:

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

Upvotes: 6

Related Questions