今天刚好做一个了相关功能
import java.util.HashMap;
import java.util.Map;
public class TestKey{
public static void main(String[] args){
Key k1 = new Key(1, 1);
Map<Key, Integer> map = new HashMap<Key, Integer>();
map.put(k1, 12);
Key k2 = new Key(1, 1);
System.out.println(map.containsKey(k2));
System.out.println(k1==k2);
}
}
class Key{
private int i;
private int j;
public Key(int i, int j){
this.i = i;
this.j = j;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + i;
result = prime * result + j;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Key other = (Key) obj;
if (i != other.i)
return false;
if (j != other.j)
return false;
return true;
}
@Override
public String toString() {
return "Key [i=" + i + ", j=" + j + "]";
}
}
true
false
一开始以为只要重写了hashCode跟equals方法后,
k1 k2两个对象是相等的,后来发现不是,
因为k1 k2都是引用,表示的是在内存堆(heap)中的一个地址,所以 k1 == k2 输出的是false
map中的get(Object key) 跟 containsKey(Object key) 的实现都是比较对象的hashCode()跟equals()来判断是否是同一个对象,而不是直接比较对象地址
而Key类里面重写了 hashCode() 跟 equals() 方法,所以实际上containsKey(k2)会返回 true
同理,get(key)也是一样