0

I am trying to implement within a class I call State some sort of mapping from a String to a set of States.

So far, I have something like this as the initialization of this concept:

Map<String, HashSet<State>> mapping = new HashMap<String, HashSet<State>>();

However, when I perform something like this:

mapping.put(transitionStringToAdd, transitionStateToAdd);

it obviously does not work because I'm not adding a HashSet to the mapping, just a member that I want to be put into the set. Would you all suggest that I create some sort of wrapper class for the HashSet or something along those lines? I need to be able to stuff distinct states into that HashSet and it's befuddling me.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by freedomflyer
1

Two ways of doing this:

1) NULL checks every time you add an element. If the "key" is not associated with any underlying set, create a new HashSet, and place it against the key.

Set<State> states = mapping.get(transitionStringToAdd);
if (states == null) {
  states = new HashSet<State>();
  mapping.put(transitionStringToAdd, states);
}
states.add(transitionStateToAdd);

2) If you can afford adding a library, Google Guava provides a class just for this use case: HashMultiMap. It relieves you of the NULL checks but of course something similar is going under the hood. The new code after using this class will look exactly the same as your code snippet.

Edited by ~s.o.s~: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.