Map中键为自定义类型时注意的问题

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
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值