Java: parameterizing a Map object

I have the following global variable:

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

I create it in my constructor as follows:

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

The above description does not compile. Apparently, when I parameterize the map, should I declare that this mapping is specifically from String to ArrayList instead of using a more general list? Any insight into why I should do this?

+3
source share
3 answers

Sorry, you cannot subclass the inner class:

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

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

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

: HashTable, , ArrayLists .

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

List, , .

+3

You can also parameterize your variable as

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

See http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#Java for more details.

+1
source

Source: https://habr.com/ru/post/1788734/


All Articles