well actually
well actually

Reputation: 12400

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?

Upvotes: 2

Views: 248

Answers (3)

Peter Taylor
Peter Taylor

Reputation: 5066

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.

Upvotes: 1

Confusion
Confusion

Reputation: 16851

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.

Upvotes: 3

Paul Tomblin
Paul Tomblin

Reputation: 182812

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>());

Upvotes: 5

Related Questions