list sublist java_Java中List集合中subList的坑

参考博主http://blog.csdn.net/xuweilinjijis/article/details/9037635

先看List接口subList方法的javadoc

The returned list is backed by this list, so non-structural

* changes in the returned list are reflected in this list, and vice-versa.

* The returned list supports all of the optional list operations supported

* by this list.

可以看到此方法其实就是直接指向原List集合中的元素,只是改变了开始位置和结束为止而已.如果修改返回对象的数据,那么原对象对应的值也会被修改。

看一下List接口具体实现类 ArrayList类,其中的subList方法源码如下

public List subList(int fromIndex, int toIndex) {

subListRangeCheck(fromIndex, toIndex, size);//检查是否越界

return new SubList(this, 0, fromIndex, toIndex);//返回截取之后的对象

}

再接着看一下 SubList类的构造器,JDK源码如下,其实 SubList就是ArrayList中的一个内部类(非静态的),

private class SubList extends AbstractList implements RandomAccess {

private final AbstractList parent;//引用调用的父集合

private final int parentOffset;//父集合的起始位置

private final int offset;//原对象的起始位置

int size;//现在集合的大小

SubList(AbstractList parent,

int offset, int fromIndex, int toIndex) {

this.parent = parent;//从此处可以看到父集合一直被子集合引用着,只要子集合存在,父集合就不会被释放。从而容易造成内存溢出

this.parentOffset = fromIndex;

this.offset = offset + fromIndex;

this.size = toIndex - fromIndex;

this.modCount = ArrayList.this.modCount;

}

}

下面是一段造成内存溢出的代码

List> cache = new ArrayList>();

try {

while (true) {

ArrayList list = new ArrayList<>();

for(int j=0;j<100000;j++) {

list.add(j);

}

List subList = list.subList(0, 1);

cache.add(subList);

}

} catch (Exception e) {

}finally {

System.out.println("Cache Size=" + cache.size());

}

运行结果

Exception in thread "main" Cache Size=815

java.lang.OutOfMemoryError: GC overhead limit exceeded

at java.lang.Integer.valueOf(Integer.java:832)

at com.effectJava.Chapter2.InstrumentedHashSet.main(InstrumentedHashSet.java:44)

看到只包含815个元素就内存溢出啦。就是因为子对象一只引用着父对象,导致父对象无法回收。从而内存溢出

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值