对象作为 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;
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-19
  • 2022-01-15
  • 2021-12-25
  • 2021-09-16
猜你喜欢
  • 2021-07-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
  • 2021-10-02
  • 2022-12-23
相关资源
相似解决方案