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

来源:互联网 发布:淘宝会员吸纳打标 编辑:程序博客网 时间:2024/05/21 10:30

------- <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这个引用所指向的位置),这个元素跑到了一个新的没有被引用所指向的区域,所以删除不掉了


原创粉丝点击