首页 > 解决方案 > ArrayList::new 中不需要的内存不足错误 - 为什么?

问题描述

我只有50000个对象时出现内存不足错误。

我检查了computeIfAbsent实现,但不幸的是没有发现任何特殊的东西。

我的机器配置是16 GBram 和core I7.

public class Test {

    public static void main(String[] args) {
        int count = 50000;
        List<ListObject> list = new ArrayList();
        for (int i = 0; i < count; i++) {
            int key = ThreadLocalRandom.current().nextInt(100000);
            int value = ThreadLocalRandom.current().nextInt(1000000);
            list.add(new ListObject(key, value));
        }
        Map<Integer, List<Integer>> map = new HashMap();
        for (ListObject a : list) {
            map.computeIfAbsent(a.getKey(), ArrayList::new);
        }
        System.out.println("Done");

    }

我的 ListObject 如下:

class ListObject {
    public ListObject(int key, int value) {
        this.key = key;
        this.value = value;
    }

    public int getKey() {
        return key;
    }

    public void setKey(int key) {
        this.key = key;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    private int key;
    private int value;

}

有人可以帮我理解这种行为。

标签: javacollectionsjava-8

解决方案


错误的部分是这样的:

ArrayList::new

你没有意识到的是,这不是推断

() -> new ArrayList<>()

但要

key -> new ArrayList<>(key)

即,每个列表都是使用从 0 到 100000 的随机大小创建的。最坏的情况是 50 亿。


推荐阅读