如何使用特定类扩展 HashMap。
public class TestMap<K, V> extends HashMap<K, V>
我希望 V 是一个整数。当使用整数时,编写 Integer 而不是 V 会覆盖 Integer 类并导致错误(Integer i = 1
不起作用)。我该如何解决这个问题?n
最佳答案
参数化扩展类并仅声明键的类型:
class IntegerMap<K> extends HashMap<K, Integer> {}
然后你可以这样做:
IntegerMap<String> integerByString = new IntegerMap<String>();
integerByString.put("0", 0);
integerByString.put("1", 1);
顺便说一句,如果您实际上是在扩展 JDK 集合类,那么它通常不被认为是一个好的样式。
通常您会编写一个从外部控制 map 的类:
class MapController<K> {
Map<K, Integer> theMap;
}
或者也许是一种以某种方式准备它的方法:
static <K> Map<K, Integer> prepMap() {
Map<K, Integer> theMap = new HashMap<>();
return theMap;
}
关于java - Java 中用特定类代替泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26950218/