对象作为 map 的 key 时,需要重写 hashCode 和 equals方法
如果没有重写 hashCode 方法,那么下面的代码示例会输出 null
我们首先定义一个对象:BmapPoint,假如这个对象只重写了 equals 方法,没有重写 hashCode 方法
package mm_test; /** * @Function: TODO ADD FUNCTION. <br/> * @Date: 2016年3月7日 下午4:29:23 * * @author zhangmengmeng01@baidu.com */ public class BmapPoint { // 经度 private double lng; // 纬度 private double lat; public BmapPoint() { } public BmapPoint(double lng, double lat) { this.lng = lng; this.lat = lat; } public boolean equals(Object obj) { if (obj instanceof BmapPoint) { BmapPoint bmapPoint = (BmapPoint) obj; return (bmapPoint.getLng() == lng && bmapPoint.getLat() == lat) ; } else { return false; } } public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } }