• java hashCode 作用


    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;
        }
    
    }
  • 相关阅读:
    DataContext.ExecuteQuery的两种方法调用
    记一次电脑被清空的感受
    JAVA学习<二>
    JAVA学习记录<一>
    iOS服务器数据请求"汉字编码"问题
    iOS上传图片问题
    iOS类型的转换
    iOS限制输入解决方法
    iOS10权限问题
    JS进阶学习<一>
  • 原文地址:https://www.cnblogs.com/newlangwen/p/9650392.html
Copyright © 2020-2023  润新知