kal*_*gne 0 java generics hashmap
我正在尝试定义我的第一个泛型类.我希望它扩展一个HashMap.它是一个LinkedHashMap,键是泛型类型,值也是泛型类型的ArrayList.
构建这个类的实例是可以的.但是当我想添加值时,编译器说
incompatible types: String cannot be converted to T_KEY
addMapValue("first", new Integer(2));
where T_KEY is a type-variable:
T_KEY extends Object declared in class FormattedMap
Run Code Online (Sandbox Code Playgroud)
我想这可能是因为我的变量T_KEY和T_VALUE没有被初始化?我该如何初始化它们?
这是我的班级:
public class FormattedMap<T_KEY, T_VALUE> extends LinkedHashMap<T_KEY, ArrayList<T_VALUE>> {
private T_KEY mapKey;
private T_VALUE mapValue;
public boolean DEBUG=false;
public FormattedMap() {
super();
}
public void addMapValue(T_KEY key, T_VALUE value) {
}
public void removeMapValue(T_KEY key, T_VALUE value) {
}
public void test(boolean b) {
addMapValue("first", new Integer(2)); // This triggers the compilor error message
}
public static void main(String [] args) {
FormattedMap<String, Integer> fm = new FormattedMap<>(); // This is fine
fm.test(true);
}
}
Run Code Online (Sandbox Code Playgroud)
让我们忘记你的主要方法.因此,该类的代码
public class FormattedMap<T_KEY, T_VALUE> extends LinkedHashMap<T_KEY, ArrayList<T_VALUE>> {
private T_KEY mapKey;
private T_VALUE mapValue;
public boolean DEBUG=false;
public FormattedMap() {
super();
}
public void addMapValue(T_KEY key, T_VALUE value) {
}
public void removeMapValue(T_KEY key, T_VALUE value) {
}
public void test(boolean b) {
addMapValue("first", new Integer(2)); // This triggers the compilor error message
}
}
Run Code Online (Sandbox Code Playgroud)
因此,您的类定义了一个test()方法,该方法addMapValue(T_KEY key, T_VALUE value)使用String和Integer作为参数调用该方法.鉴于您的类是通用的,泛型类型可以是任何类型.不一定是String和Integer.所以这个方法无法编译.
此外,您的类还定义了两个完全无用的字段mapKey和mapValue.
代码应该是instezad:
public class FormattedMap<T_KEY, T_VALUE> extends LinkedHashMap<T_KEY, ArrayList<T_VALUE>> {
public FormattedMap() {
super();
}
public void addMapValue(T_KEY key, T_VALUE value) {
}
public void removeMapValue(T_KEY key, T_VALUE value) {
}
public static void main(String [] args) {
FormattedMap<String, Integer> fm = new FormattedMap<>(); // This is fine
fm.addMapValue("first", new Integer(2));
// this is valid, because fm is of type FormattedMap<String, Integer>
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,无论如何,扩展LinkedHashMap肯定是一个坏主意.你的类应该有一个LinkedHashMap,而不是一个LinkedHashMap.