Changing key in HashMap

I

Ike

I have a situation whereby I may have to change a key in a HashMap. Is there
a better way to do this than to obtain the object associated with that key,
put() a new entry in the HashMap with the old object and the new key, then
delete the old HashMap entry? TIA, Ike
 
R

Robert Klemme

I have a situation whereby I may have to change a key in a HashMap. Is there
a better way to do this than to obtain the object associated with that key,
put() a new entry in the HashMap with the old object and the new key, then
delete the old HashMap entry? TIA, Ike

You can do

V x = map.remove(oldKey);
map.put(newKey, x);

Note: you may have to change the code depending on whether you allow
null values in the map and / or you cannot be sure that oldKey actually
exists in the map.

Regards

robert
 
P

Patricia Shanahan

Ike said:
I have a situation whereby I may have to change a key in a HashMap. Is there
a better way to do this than to obtain the object associated with that key,
put() a new entry in the HashMap with the old object and the new key, then
delete the old HashMap entry? TIA, Ike

No, I don't think there is a better way to do it.

The change of key will probably cause a change in bucket, so even if
there were a method to do it, HashMap would have to remove the old
key-value pair from one bucket, and insert with the new key it its
appropriate bucket.

Patricia
 
M

Mike Schilling

Ike said:
I have a situation whereby I may have to change a key in a HashMap. Is
there a better way to do this than to obtain the object associated with
that key, put() a new entry in the HashMap with the old object and the new
key, then delete the old HashMap entry? TIA, Ike

Assuming that the change affects either equals() or hashCode(), then, no,
there's no better way. If the change doesn't affect either of those
methods, then there's no need to do anything.
 
A

Adam Maass

Ike said:
I have a situation whereby I may have to change a key in a HashMap. Is
there a better way to do this than to obtain the object associated with
that key, put() a new entry in the HashMap with the old object and the new
key, then delete the old HashMap entry? TIA, Ike

Well, other than a minor optimization, not really:


Map m...

void replace(Object oldKey, Object newKey){
m.put(newKey, m.remove(oldKey));
}

The 'remove' method returns the value, if any, associated with the key that
was removed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,263
Messages
2,571,064
Members
48,769
Latest member
Clifft

Latest Threads

Top