-2

for example I want to edit the key that is 2 in this map and make it 3, how can I do that?

Map<Integer,Integer>map=new HashMap<>();
map.put(2,2);
map.get(2)=3;

alex
  • 1
  • 1

3 Answers3

1

You can't. You would have to remove the old entry with the old key and add a new one with the new key but the same value

Map<Integer,Integer>map=new HashMap<>();
map.put(2,2);
var removed = map.remove(2);
map.put(3, removed);
Marcus Dunn
  • 487
  • 3
  • 7
0

Your code says that what you want to do is like map.get(2) = 3, which isn't rewriting the key -- it's updating the value for the key 2.

To do that, you just need map.put(2, 3).

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

Maps have unique keys. You simply need to write:

map.put(2, 3); 

to change your value for key=2;

Sasa Arsenovic
  • 286
  • 2
  • 5