我有一個類,我試圖用來測試HashMap和TreeMap,如下所示;使用Java中的通用映射問題
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()方法;
的方法放(關鍵字類型,值類型)在類型地圖是不適用的參數(字符串,整數)
我沒有收到任何其他警告,我不明白爲什麼我得到這個?這不是泛型的全部點嗎?一般定義並具體實現?
感謝您的幫助!
另外,泛型類型參數通常限制爲單個大寫字母,例如。 '公共課MyClass {'。通常使用「E」或「T」,對於地圖使用「K」和「V」。 –
Dunes