地图的通用方法

时间:2013-04-16 23:11:06

标签: java generics

除了参数部分之外,这两种方法的实现完全相同。我想知道我是否可以使用通用版本的Java方法将这两种方法统一为一体。有可能或最好的方法是什么?我正在考虑使用通用T或Object类型作为两种情况的映射键。

void mapPopulator1 (Map<String, Integer> map, String key)
{
    Integer value = map.get(key);
    if (value != null) {
        value = Integer.valueOf(value.intValue() + 1);
    }
    else {
        value = Integer.valueOf(1);
    }
    map.put(key, value);
}

void mapPopulator2 (Map<EventObj, Integer> map, EventObj key)
{
    Integer value = map.get(key);
    if (value != null) {
        value = Integer.valueOf(value.intValue() + 1);
    }
    else {
        value = Integer.valueOf(1);
    }
    map.put(key, value);
}

1 个答案:

答案 0 :(得分:4)

是的,您可以使用通用方法。

<T> void mapPopulatorGeneric(Map<T, Integer> map, T key)

这会使用T声明泛型类型<T>,然后将其用作参数类型。

相关问题