2

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?

1
  • You should look into the Guava Multimap. Specifically, the ListMultimap implementation. Commented Jan 29, 2011 at 21:37

3 Answers 3

5

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>());
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.