HashMap基本概念
HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。一个key对应一个value,key不能重复,value可以重复。
![](https://img-blog.csdnimg.cn/img_convert/d12f7eb5328709790ad26a74ba6b102c.png)
在HashMap中,put方法是将键值对通过哈希函数计算存放地址后存放进散列表中,使用put方法时会出现两种情况,当散列表中没有key的地址时,表示没有这个key,直接将键值对存入散列表中;如果已经存在这个key,会将原来键值对中的value替换成后面的value。
![](https://img-blog.csdnimg.cn/img_convert/18deaee2b17a40b3fb092432580acbf2.png)
问题
HashMap能够通过key来修改值。那能不能只修改key不修改value呢?
解题过程
事实上HashMap中没有提供直接修改key的方法,只能通过put(newKey,value)方法创建新的键值对达到修改key的目的,这样Map中就会出现两个值相同的键值对。
Map<String, String> map = new HashMap<>();
map.put("key","value");
System.out.printf(String.valueOf(map));
map.put("newkey","value");
System.out.printf(String.valueOf(map));
然后通过remove删除旧的键值对就达到修改key的目的。
![](https://img-blog.csdnimg.cn/img_convert/896524cad86d706d90fbc97c9722dd64.png)
但这样太麻烦,有没有直接修改key的方法呢?
结论是没有,HashMap不允许修改key,只能通过添加新键删除旧键的方法。
既然HashMap不允许直接修改key,那能不能修改key本身达到修改key的目的呢?比如我们使用一个对象作为键的时候,在Map添加键值对之后在去使用对象本身的修改方法修改对象,能不能成功修改键呢?
Map<List,String>map=new HashMap<>();
List<String> l=new ArrayList<>();
l.add("zxc");
map.put(l,"zxc");
System.out.println(map);
l.add("asd");
System.out.println(map);
![](https://img-blog.csdnimg.cn/img_convert/9fb1dc9b57e1d6ec3fd63f5f3ea09f5c.png)
输出成功,在只修改了key自身的情况下,value没有发生改变,键值对也没有发生改变。通过这种方法达到了最开始的目的,修改key而不修改value。但此时也发生了疑惑,key发生了改变后能不能正常的使用map的方法呢?测试一下map中的常用方法:
Map<List,String>map=new HashMap<>();
List<String> l=new ArrayList<>();
l.add("zxc");
map.put(l,"zxc");
System.out.println(map);
l.add("asd");
System.out.println(map);
System.out.println(map.get(l));
![](https://img-blog.csdnimg.cn/img_convert/48d8887f04f49e6794b28ee7e9c113b3.png)
哦豁!发现get(key)的方法得到的值为null,没有找到对应的值了,这是为什么呢?
通过查询底层代码具体实现
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
public V get(Object key) {
Node<K,V> e;
return (e = getNode(key)) == null ? null : e.value;
}
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
发现HashMap在put时不仅只是存入key和value的信息,同时还放入了key的HashCode,get的时候也是会根据key的HashCode查询键值对的信息。
Map<List,String>map=new HashMap<>();
List<String> l=new ArrayList<>();
l.add("zxc");
System.out.println(l.hashCode());
map.put(l,"zxc");
// System.out.println(map);
l.add("asd");
System.out.println(l.hashCode());
![](https://img-blog.csdnimg.cn/img_convert/5922df850fbe7513f033fb5a96291a38.png)
显示集合修改前后的HashCode,发现两者的值并不相同,说明key前后的HashCode是发生了改变的,所以无法通过key的HashCode进行查询。直接通过key需要key的HashCode的方法都受到影响。
那为什么直接输出map能输出呢?
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
直接输出的Map是使用键值对显示的方式输出,中间没有key的HashCode的参与,所以没有发生变化,那是不是通过键值对的方式没有受到影响呢?我们通过键值对的遍历方式测试一下:
Map<List,String>map=new HashMap<>();
List<String> l=new ArrayList<>();
l.add("zxc");
map.put(l,"zxc");
Set<Map.Entry<List, String>> oldentries = map.entrySet();
for (Map.Entry<List, String> m:oldentries) {
System.out.println(m.getValue());
System.out.println(m.getKey());
System.out.println(m);
}
l.add("asd");
Set<Map.Entry<List, String>> newentries = map.entrySet();
for (Map.Entry<List, String> m:newentries) {
System.out.println(m.getValue());
System.out.println(m.getKey());
System.out.println(m);
}
![](https://img-blog.csdnimg.cn/img_convert/72b09b57efd760ec56b93f36d0e10ce7.png)
通过前后对比发现通过键值对的获取方式可以正常获取,没有受到影响。
结论
通过上述的实际解题和得出的结果,我们可以得到前面问题的结论:
HashMap中存放键值对(key-value)映射。一个key对应一个value,value可以通过key进行修改,HashMap没有提供修改key的方法。可以通过key自身提供的方法进行修改。修改后如果key的HashCode发生了变化,那么通过key的HashCode的方法都将受到影响。而没有使用key的HashCode直接使用键值对对象的方法不受影响,可以正常使用。