Is it possible to update the values in hashmap or add new elements when iterating over it? -
i have hashmap, , want update values when iterating on it, , if possible add new elements. believe throw concurrentmodification exception. so, there way achieve or it's not possible?
as far know best can removing , updating values while cycling. try following
public static void main(string[] args) { hashmap<string, string> map = new hashmap<string, string>(); map.put("one", "lemon"); map.put("two", "orange"); map.put("three", "kiwi"); iterator<entry<string, string>> = map.entryset().iterator(); while (it.hasnext()) { map.entry entry = (map.entry) it.next(); string key = (string)entry.getkey(); //removal if(key.equals("one")) it.remove(); //update if(key.equals("two")) entry.setvalue("lime"); } } inserting new element in map cause exception. if need so, should fill second hashmap values of first, , modify @ will. in other words, can build second hashmap while cycling on first, , can manage needed flexibility.
Comments
Post a Comment