Reputation: 171
hello guys how can I change the value of a key in HashMap
?
look at this please :
private static final Map<String, DefaultMutableTreeNode> M = new HashMap<>();
public static DefaultMutableTreeNode executeCommand(int command, String item1, String item2) {
switch (command) {
//...
case CommandsList.CREATE_CHILD:
String name = item1;
M.put(name, new DefaultMutableTreeNode(name));
//...
return M.get(root);
case CommandsList.CHANGE_NAME:
String newName = item2;
//
//what should I do here to replace name with newName???
//
return M.get(root);
//...
}
return null;
}
Upvotes: 1
Views: 1754
Reputation: 171
hey guys thank you all for helping...finally the problem was solved :))
M.put(item2, M.remove(item1));
M.get(item2).setUserObject(new DefaultMutableTreeNode(item2));
Upvotes: 0
Reputation: 2301
I'm assuming that "item1" variable being passed into the method is the key for the map, i.e. the old name. And now you want the map updated with "item2" which is the new name. If this is correct, you can remove the old name and then add the new one:
map.remove(item1);
map.put(item2, new DefaultMutableTreeNode(item2));
If instead it is the case, perhaps, that you just want to replace the value in the map located at item1 with the new name which is in the variable item2, then simply put again and the new item2 value will overwrite what is in the map at the key item1:
map.put(item1, new DefaultMutableTreeNode(item2));
I hope one of these is what you're after. Please let us know which one works, if any do, and mark as correct answer if so!
Upvotes: 1
Reputation: 10945
You cannot change the value of the key directly, but you can easily re-add the value under a new key like this:
map.put(newkey, map.remove(oldkey));
Upvotes: 8