是否可以重命名Hashmap密钥?

时间:2022-03-01 10:46:57

I'm looking for a way to rename a Hashmap key, but i don't know if it's possible in Java.

我正在寻找一种重命名Hashmap密钥的方法,但我不知道它是否可以在Java中使用。

5 个解决方案

#1


95  

Try to remove the element and put it again with the new name. Assuming the keys in your map are String, it could be achieved that way:

尝试删除元素并使用新名称再次添加。假设地图中的键是String,则可以通过以下方式实现:

Object obj = map.remove("oldKey");
map.put("newKey", obj);

#2


12  

Assign the value of the key, which need to be renamed, to an new key. And remove the old key.

将需要重命名的密钥值分配给新密钥。并删除旧密钥。

hashMap.put("New_Key", hashMap.get("Old_Key"));
hashMap.remove("Old_Key");

#3


6  

hashMap.put("New_Key", hashMap.remove("Old_Key"));

This will do what you want but, you will notice that the location of the key has changed.

这将做你想要的,但你会注意到键的位置已经改变。

#4


4  

You don't rename a hashmap key, you have to insert a new entry with the new key and delete the old one.

您不重命名hashmap键,您必须使用新键插入新条目并删除旧键。

#5


4  

You cannot rename/modify the hashmap key once added.

添加后,您无法重命名/修改hashmap键。

Only way is to delete/remove the key and insert the new key and value pair.

唯一的方法是删除/删除密钥并插入新的密钥和值对。

Reason : In hashmap internal implementation the Hashmap key modifier marked as final.

原因:在hashmap内部实现中,Hashmap键修饰符标记为final。

static class Entry<K ,V> implements Map.Entry<K ,V>
{
 final K key;
 V value;
 Entry<K ,V> next;
 final int hash;
...//More code goes here
}

For Reference : HashMap

供参考:HashMap

#1


95  

Try to remove the element and put it again with the new name. Assuming the keys in your map are String, it could be achieved that way:

尝试删除元素并使用新名称再次添加。假设地图中的键是String,则可以通过以下方式实现:

Object obj = map.remove("oldKey");
map.put("newKey", obj);

#2


12  

Assign the value of the key, which need to be renamed, to an new key. And remove the old key.

将需要重命名的密钥值分配给新密钥。并删除旧密钥。

hashMap.put("New_Key", hashMap.get("Old_Key"));
hashMap.remove("Old_Key");

#3


6  

hashMap.put("New_Key", hashMap.remove("Old_Key"));

This will do what you want but, you will notice that the location of the key has changed.

这将做你想要的,但你会注意到键的位置已经改变。

#4


4  

You don't rename a hashmap key, you have to insert a new entry with the new key and delete the old one.

您不重命名hashmap键,您必须使用新键插入新条目并删除旧键。

#5


4  

You cannot rename/modify the hashmap key once added.

添加后,您无法重命名/修改hashmap键。

Only way is to delete/remove the key and insert the new key and value pair.

唯一的方法是删除/删除密钥并插入新的密钥和值对。

Reason : In hashmap internal implementation the Hashmap key modifier marked as final.

原因:在hashmap内部实现中,Hashmap键修饰符标记为final。

static class Entry<K ,V> implements Map.Entry<K ,V>
{
 final K key;
 V value;
 Entry<K ,V> next;
 final int hash;
...//More code goes here
}

For Reference : HashMap

供参考:HashMap