黑马程序员——面试重点之内存泄露

------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

内存泄漏也称作“存储渗漏”,用动态存储分配函数动态开辟的空间,在使用完毕后未释放,结果导致一直占据该内存单元。直到程序结束。即所谓内存泄漏。简单地说就是申请了一块内存空间,使用完毕后没有释放掉。它的一般表现方式是程序运行时间越长,占用内存越多,最终用尽全部内存,整个系统崩溃。由程序申请的一块内存,且没有任何一个指针指向它,那么这块内存就泄露了

package com.baidu.first;


public class ReflectPoint {
    public String str1;
    public int i;
    public String str2="asdfghaaa";
    public ReflectPoint(String str1, int i) {
        super();
        this.str1 = str1;
        this.i = i;
    }
    public String toString()
    {
        return str1+":"+str2;
    }
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + i;
        result = prime * result + ((str1 == null) ? 0 : str1.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ReflectPoint other = (ReflectPoint) obj;
        if (i != other.i)
            return false;
        if (str1 == null) {
            if (other.str1 != null)
                return false;
        } else if (!str1.equals(other.str1))
            return false;
        return true;
    }

}


package com.baidu.first;
import java.util.*;

public class ReflectText1 {
    public static void main(String[] args){
        Collection collection=new HashSet();
        ReflectPoint rft1=new ReflectPoint("asd",3);
        ReflectPoint rft2=new ReflectPoint("asdf",4);
        ReflectPoint rft3=new ReflectPoint("asds",3);
        collection.add(rft1);
        collection.add(rft2);
        collection.add(rft3);
        collection.add(rft1);
        rft1.i=8;//哈希集合中的元素被修给后该对象就移除不掉了,这就叫内存泄露也叫做内存渗漏
        collection.remove(rft1);
        System.out.println(collection.size());
    }

}

在这个例子中造成内存渗漏的原因是修改了决定哈希值的字段,导致这个元素不在哈希集合原来的区域(rft1这个引用所指向的位置),这个元素跑到了一个新的没有被引用所指向的区域,所以删除不掉了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值