在HashMap中的get(Object key)的执行流程
在HashMap中get(Object key)
- 计算key的hashcode(),等到一个整数n
- 然后用这个n%(length)【length代表当前map的最大的容量】=index
- 用index作为下标,得到hashmap内部的桶的结构中位于index处的链表list(Java1.8中有可能是红黑树,这里用链表代替。)
- 然后循环遍历列表,直到能够equals(key),输出当前值的value
通过上面可以知道,hashcode是为了确定在桶中的位置,而equals是了区别链表中的内容。
不重写hashcode()使用默认的Object的hashcode()方法
public class Solution {
public int a;
public Solution(int val){
this.a = val;
}
public static void main(String[] args){
HashMap<Solution,Integer> test = new HashMap<Solution,Integer>();
Solution s1 = new Solution(1);
test.put(s1, 1);
System.out.println(test.get(new Solution(1)));//输出null
}
}
这是因为Object中默认的hashcode()的是输出对象在堆上的地址。所以两个对象不一样的内容,所以存储在map中内部桶的位置也是不同的。