2014-07-23 149 views
0

我想要定义我的第一个泛型类。我想要它扩展一个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 

我想这可能是由于这样的事实,我的变量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); 

    } 
} 

回答

5

让我们忘记你的主要方法。该类的代码是这样

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

所以,你的类定义了一个test()方法,它调用一个字符串和一个整数作为参数的方法addMapValue(T_KEY key, T_VALUE value)。鉴于你的类是通用的,通用类型可以是任何东西。不一定是字符串和整数。所以这个方法不能编译。

此外,你的类还定义了两个完全没用的字段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> 
    } 
} 

注意扩展LinkedHashMap的肯定是一个坏主意呢。你的类应该有一个LinkedHashMap,而不是一个LinkedHashMap。

+0

非常感谢!事情现在更清晰了。当然,现在我可以看到我的test()方法没有任何意义。 – kaligne

0

这是因为不兼容的函数签名 addMapValue的( “第一”,新的整数(2));

1

在您的test()函数中,编译器无法确定此特定实例是否为<String, Integer>。所以编译错误。

例如,这会工作:

public static void main(String [] args) { 
    FormattedMap<String, Integer> fm = new FormattedMap<>(); // This is fine 
    // fm.test(true); 
    fm.addMapValue("first", new Integer(2)); 
} 

如果test()static,实例为参数,并作为参数传递,这将工作太:

public static void test(FormattedMap<String, Integer> instance) { 
    instance.addMapValue("first", new Integer(2)); 
} 

的一点是,你目前假定通用类型是StringInteger中的一段代码,预计这些类型是通用的。

+1

谢谢你的回答,我现在明白了:) – kaligne