Take the 2-minute tour ×

I'm not able to navigate down to the HashSets in my datastructure

I declared an array of Map[] and populated it with HashMap with K of Integer, and V of HashSet of String but was unable to add items to the HashSet.

I've trimmed the code down to illustrate ...

private Map[] myMaps = null;

myMaps = new Map[numRepeats];
myMaps[0] = new HashMap<Integer,HashSet<String>>();
myMaps[0].put(0, new HashSet<String>());

The popup in NetBeans shows I can get to java.util.Map with


but using the map.get(0) method I thought would return the HashSet


shows I've got to generic java.lang.object, not to the HashSet. Since I need to use the HashSet.add() method next this means I'm stuck. I would appreciate suggestions.

Thank you

share|improve this question
You have an array of maps of sets? You need some classes in there, or you're going to be tearing your hair out while debugging! –  corsiKa Feb 20 '11 at 18:39
add comment

3 Answers

up vote 0 down vote accepted

When you define your map, you could define it with the full types involved, so:

private Map<Integer, HashSet<String>>[] myMaps = null;

Then, you wouldn't have to cast it back (assuming all your maps in myMaps will be of that type).

share|improve this answer
Thank you - assumption right, so I did this - it worked! (-: –  bobox Feb 20 '11 at 19:08
add comment

Unfortunately, Java Generics make it rather tricky to have an array of a generic class. However, it is possible, and it will solve your problem in a typesafe way.

1st. declare your map like this

private Map<Integer,Set<String>>[] myMaps = null;

2nd. use a utility function to allocate

public static <T> T[] newMapArray( int size )
    return (T[])java.lang.reflect.Array.newInstance(Map.class, size);

3rd. allocate myMaps like this

myMaps = newMapArray(numRepeats);
share|improve this answer
Thanks. umm, it's early days in Java for me and that looks a plateful. I'll study it and read around the suggestion. In the meantime I'm using Map<Integer, HashSet<String>>[] myMaps = null; (because I understand it).thanks –  bobox Feb 20 '11 at 19:14
@bobox I certainly can understand why that looks intimidating. The nice thing about it is you can put it in some utility class and reuse it anywhere you like. Also, it hides the unchecked casts. –  karoberts Feb 20 '11 at 19:53
add comment

You need to cast it to HashMap<Integer,HashSet<String>>.

share|improve this answer
Thanks, there's a consensus with Dante617 that this is the way fwd –  bobox Feb 20 '11 at 19:09
add comment

Your Answer


