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 no开发者_运维技巧t 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?
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>());
It's rather the reverse: when you create the new HashTable, you don't have to specify that you're going to be using ArrayLists as values. Instead, you should say
new Hashtable<String, List<String>>();
and the choice of the List implementation(s) you are going to use as values remains free.
You could also parameterise your variable as
private Map<String, ? extends List<String>> network;
See e.g. http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#Java for more details.
精彩评论