在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中内部桶的位置也是不同的。
不重写hashcode方法
public class Solution {
public int a;
public Solution(int val){
this.a = val;
}
@Override
public boolean equals(Object k){
if(this == k){
return true;
}
if(k instanceof Solution){
Solution s = (Solution)k;
return ((Solution) k).a == s.a;
}
return false;
}
public static void main(String[] args){
HashMap<Solution,Integer> test = new HashMap<Solution,Integer>();
Solution s1 = new Solution(1);
Solution s2 = new Solution(1);
test.put(s1, 1);
test.put(s2, 2);
System.out.println(test.get(s1));//1
System.out.println(test.get(s2));//2
}
}
输出结果是 1,2 这样的情况下map里面的key应该是唯一的,这样却失去了唯一性。
都重写
public class Solution {
public int a;
public Solution(int val){
this.a = val;
}
@Override
public boolean equals(Object k){
if(this == k){
return true;
}
if(k instanceof Solution){
Solution s = (Solution)k;
return ((Solution) k).a == s.a;
}
return false;
}
@Override
public int hashCode(){
return this.a*10;
}
public static void main(String[] args){
HashMap<Solution,Integer> test = new HashMap<Solution,Integer>();
Solution s1 = new Solution(1);
Solution s2 = new Solution(1);
test.put(s1, 1);
test.put(s2, 2);
System.out.println(test.get(s1));//2
System.out.println(test.get(s2));//2
}
}
输出的都是2,这是因为在源码当中对于hashmap的put方法有值的情况下,第二次put是更新当前的值,并且返回原来的值。
改天写一下HashMap的源码就全都明白了。