首页 > 编程语言 > 详细

java hashCode 作用

时间:2018-09-15 12:15:54      阅读:178      评论:0      收藏:0      [点我收藏+]

hashCode 作用,对象根据hashCode的值分区域存放

/**
 * hashCode 作用
 * 
 * @author Administrator
 * 
 */
public class Point {

    public static void main(String[] args) {
        Point p1 = new Point(3, 3);
        Point p2 = new Point(2, 3);
        Point p3 = new Point(3, 3);

        HashSet<Point> set = new HashSet<>();

        set.add(p1);
        set.add(p2);
        set.add(p3);
        set.add(p1);
        p1.x = 7;
        // 修改equals 中的变量的值,hashCode改变,查找的hash区域变化,在新计算的区域p1无法找到,无法删除,最后可能引起内存泄漏
        set.remove(p1);
        System.out.println(set.size());
    }

    int x;

    int y;

    public Point(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Point other = (Point) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }

}

 

java hashCode 作用

原文:https://www.cnblogs.com/newlangwen/p/9650392.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!