I have the following code which adds some arrays to a hashmap but then I want access those arrays to do some work on them later. I’ve gotten this far but can’t figure the rest out to make it work….
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
public static void main(String[] args) {
String[][] layer1 = {
{"to1", "TYPE1", "start"},
{"to2", "TYPE1", "start"}
};
String[][] layer2 = {
{"to3", "TYPE2" ,"item1"},
{"to3", "TYPE2" ,"item2"}
};
HashMap<String,Object> hashMap = new HashMap<String,Object>();
hashMap.put("layer1", layer1);
hashMap.put("layer2", layer2);
Iterator<Entry<String, Object>> iterator = hashMap.entrySet().iterator();
while(iterator.hasNext()){
hashMap.values().toArray();
for (???) {
// lets print array here for example
}
}
}
Smells like homework, but a few suggestions –
<String,Object>– make it<String, String[][]>, as that’s what you’re storing.You’re iterating twice. You either
– iterate through the map, either the keys, values or entries. Each item is an iterator return value, e.g.
hashmap.values.toArray gives you all of the contents, which is the same thing your iterator is doing.
if you’re only iterating through the contents, then you’re not really using a map, as you’re never making use of the fact that your values are available by key.