• 重写hashCode方法,导致内存泄漏


    package com.nchu.learn.base.reflect;
    
    import org.junit.Test;
    
    import java.util.Collection;
    import java.util.HashSet;
    
    /**
     * @Decription 反射学习
     * @Author yangsj
     * @Date 20190711 11:10
     **/
    public class ReflectDemo {
        /**
         * 重写hashcode方法后,修改成员字段数值会影响hashcode值,进而影响到对象在哈希表中的位置,致使remove方法无法找到原来的对象,但是,对象有在哈希表中有引用,hash对象又没有被释放。垃圾回收器发现其还有引用,又不会回收该对象。于是,内存泄漏了。
         * 重写hashcode方法的类对象,在放入hash表后,一定要谨慎操作对象字段属性值。如果要修改,先从哈希表中删除该对象,修改后再放入哈希表。
         */
        @Test
        public void Test1(){
            Collection collections = new HashSet();
    
            ReflectPoint rpt1 = new ReflectPoint(3,3);
            ReflectPoint rpt2 = new ReflectPoint(5,5);
            ReflectPoint rpt3 = new ReflectPoint(3,3);
    
            collections.add(rpt1);
            collections.add(rpt2);
            collections.add(rpt3);
            collections.add(rpt1);
            System.out.println(collections.size());
    
            //重写javabean的 hashCode()方法,此方法产生的haseCode与对象中的成员字段值有关。
            //改变实例参与hashCode运算的字段,会导致该实例的hashCode发生变化
            rpt1.y = 8;
            //1、由于找不到此hashcode对应的index,remove不做任何操作。
            //2、从hashset中删除了一个与之修改后生成对象的hashcode相等的对象。
            collections.remove(rpt1);
    
            System.out.println(collections.size());
    
    
        }
    }
    package com.nchu.learn.base.reflect;
    
    /**
     * @Decription TODO
     * @Author yangsj
     * @Date 20190711 11:14
     **/
    public class ReflectPoint {
        private int x;
        public int y;
        public ReflectPoint(int x, int y) {
            super();
            this.x = x;
            this.y = y;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            ReflectPoint that = (ReflectPoint) o;
    
            if (x != that.x) return false;
            return y == that.y;
        }
    
        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }
    
        public int getX() {
            return x;
        }
    
        public void setX(int x) {
            this.x = x;
        }
    
        public int getY() {
            return y;
        }
    
        public void setY(int y) {
            this.y = y;
        }
    }

     2

     2

  • 相关阅读:
    Oracle约束详解
    查看oracle数据库中表是否被锁
    Oracle安装EMCC
    Hbuilder和夜神模拟器的使用
    Python3 进制表示、进制转换
    Python3制作图片缩略图
    flask 异步接口
    git——一段代码将本地的代码提交至远程
    centos7防火墙放开某一端口
    CentOS7安装docker
  • 原文地址:https://www.cnblogs.com/realshijing/p/11169802.html
Copyright © 2020-2023  润新知