I have a class which I am trying to use to test HashMap and TreeMap, shown below;
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)
{
}
}
}
In the attempted call to the put() method I am receiving the below error message;
The method put(KeyType, ValueType) in the type Map is not applicable for the arguments (String, int)
I am not receiving any other warnings, and I don’t understand why I am getting this? Isn’t this the entire point of generics? To define generically and implement concretely?
Thanks for any assistance!
The
test()method is part of theTestMapclass. In any of theTestMapmethods, you can only reference the generic type, not any specific type (because this depends on the individual instance). However, you can do this: