Ale*_*eon 120
尝试删除元素并使用新名称再次添加.假设地图中的键是String,可以通过以下方式实现:
Object obj = map.remove("oldKey");
map.put("newKey", obj);
Run Code Online (Sandbox Code Playgroud)
Dee*_*ani 18
将需要重命名的密钥值分配给新密钥.并删除旧密钥.
hashMap.put("New_Key", hashMap.get("Old_Key"));
hashMap.remove("Old_Key");
Run Code Online (Sandbox Code Playgroud)
Moh*_*hbi 13
hashMap.put("New_Key", hashMap.remove("Old_Key"));
Run Code Online (Sandbox Code Playgroud)
这将做你想要的,但你会注意到键的位置已经改变.
添加后,您无法重命名/修改hashmap 键.
唯一的方法是删除/删除密钥并插入新的密钥和值对.
原因:在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
}
Run Code Online (Sandbox Code Playgroud)
供参考:HashMap
| 归档时间: |
|
| 查看次数: |
71087 次 |
| 最近记录: |