i am a newbie in Java (coming from JavaScript developing on Adobe LiveCycle) and facing the following problem:
I have a String array with several items. I want to put only the items with the value "a" to a HashMap. But instead of 3 "a" values in the HashMap i get 1 null value there. Why is that?
String[] s = {"a", "a", "b", "a"};
Map m = new HashMap();
for (int i = 0; i < s.length; i++) {
if (s[i].equals("a")) {
m.put(i, s[i]);
}
}
for (int i = 0; i < m.size(); i++) {
System.out.println(m.get(i));
}
// Prints
//a
//a
//null
Map<Integer, String>where key is the index of the string in the array. You shouldn't iterate from 0 to map size, but over map's actual entries. Usefor (Integer key : map.keySet())Map, i.e. you have aMapwith content{0=a, 1=a, 3=a}. Therefore, if you try to access the map with2in them.get(...), you get anullsince key2is not found in the map. On a sidenote: you are using raw types. You should bind the types of theMapandHashMapproperly:Map<Integer, String> m = new HashMap<Integer, String>();m.get(i)Returns the value for keyi. there you have no index like an array