Search code examples
javapolymorphismparameterized

Java: parameterizing Map object


I have the following global variable:

private Map<String,List<String>> network;

I instantiate it in my constructor like this:

network = new Hashtable<String,ArrayList<String>>();

The above instantiation does not compile. Apparently when I parametrize the Map, I must declare that it is a mapping specifically from String to ArrayList instead of using the more general List? Any insight as to why I must do this?


Solution

  • Sorry, you can't subclass the internal class:

    network = new Hashtable<String,List<String>>();
    

    But when you add a member, you can create the value as an arraylist.

    network.put("Key", new ArrayList<String>());