重写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

posted @ 2019-07-11 14:31  Wayfo  阅读(708)  评论(0编辑  收藏  举报