2

我有一个类,我试图用它来测试 HashMap 和 TreeMap,如下所示;

public class TestMap<KeyType, ValueType>
{
private Map<KeyType, ValueType> internalMap;

/*
 * Entry point for the application
 */
public static void main( String [ ] args )
{
    TestMap<String, Integer> testHashMap = new TestMap<String,Integer>(new HashMap<String, Integer>());
    testHashMap.test();

    TestMap<String, Integer> testTreeMap = new TestMap<String,Integer>(new TreeMap<String, Integer>());
    testTreeMap.test();
}    

/*
 * Constructor which accepts a generic Map for testing
 */
public TestMap(Map<KeyType, ValueType> m)
{
    this.internalMap = m;
}   

public void test()
{
    try
    {
        //put some values into the Map
        this.internalMap.put("Pittsburgh Steelers", 6);

        this.printMap("Tested Map", this.internalMap);  
    }
    catch (Exception ex)
    {

    }
}

}

在尝试调用 put() 方法时,我收到以下错误消息;

类型 Map 中的 put(KeyType, ValueType) 方法不适用于参数 (String, int)

我没有收到任何其他警告,我不明白为什么会收到这个?这不是泛型的全部意义吗?通用定义和具体实现?

感谢您的帮助!

4

3 回答 3

4

test()方法是TestMap类的一部分。在任何TestMap方法中,您只能引用泛型类型,而不是任何特定类型(因为这取决于单个实例)。但是,您可以这样做:

public static void main( String [ ] args )
{
    TestMap<String, Integer> testHashMap = new TestMap<String,Integer>(new HashMap<String, Integer>());
    testHashMap.internalMap.put("Pittsburgh Steelers", 6);

    TestMap<String, Integer> testTreeMap = new TestMap<String,Integer>(new TreeMap<String, Integer>());
    testTreeMap.internalMap.put("Pittsburgh Steelers", 6);
}
于 2012-10-07T20:55:12.037 回答
3

问题是您的整个类是通用的,但是您正在尝试使用一组特定的类型对其进行测试。尝试将测试方法移出对象并在TestMap<String, int>.

于 2012-10-07T20:51:18.863 回答
1

另一种选择是从您的 TestMap 对象中删除泛型。他们目前似乎没有做任何事情。

public class TestMap {
    private Map<String, Integer> internalMap;

    /*
     * Entry point for the application
     */
    public static void main( String [ ] args )
    {
        TestMap testHashMap = new TestMap(new HashMap<String, Integer>());
        testHashMap.test();

        TestMap testTreeMap = new TestMap(new TreeMap<String, Integer>());
        testTreeMap.test();
    }

    /*
     * Constructor which accepts a generic Map for testing
     */
    public TestMap(Map<String, Integer> m)
    {
        this.internalMap = m;
    }   

    public void test()
    {
        try
        {
            //put some values into the Map
            this.internalMap.put("Pittsburgh Steelers", 6);

            this.printMap("Tested Map", this.internalMap);  
        }
        catch (Exception ex)
        {

        }
    }
}
于 2012-10-07T20:57:40.963 回答