开发者

Java: parameterizing Map object

开发者 https://www.devze.com 2023-02-07 05:22 出处:网络
I have the following global variable: private Map<String,List<String>> network; I instantiate it in my constructor like this:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消