Map的get()源码如下:
public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode()); //返回key对应的hash值
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) { // 调用equals()逐个比较key集合中有无与形参相同的键值
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
当Map的key是自定义的对象类型时,要在自定义类中,重载Object类的两个方法,hashCode()和equals(),使得满足自己定义的“相同”的含义,这样才能用“相同”的key取到合适的value。
例子:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString(){
return "["+x+" , "+y+"]";
}
public static void main(String[] args){
Map<Point,Integer> m=new Map<Point,Integer>();
m.put(new Point(1,2),3);
System.out.println(m.get(new Point(1,2));// result: null
}
}
以上代码的不足之处是没有重载hashCode和equals方法,纠正如下:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString(){
return "["+x+" , "+y+"]";
}
public boolean equals(Object o){
System.out.println(">> in Point.equals()");
if(((Point)o).getX()==x && ((Point)o).getY()==y)
return true;
return false;
}
public int hashCode(){
System.out.println(">> in Point.hashCode()");
return x*10+y;
}
public static void main(String[] args){
Map<Point,Integer> m=new Map<Point,Integer>();
m.put(new Point(1,2),3);
System.out.println(m.get(new Point(1,2));// result: 3
}
}