我仅使用 50000 对象就出现内存不足错误。
我检查了computeIfAbsent
实现但不幸的是没有发现任何奇怪的事情。
我的机器配置是16 GB
内存和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;
}
有人可以帮助我理解这种行为吗?
最佳答案
错误部分是这样的:
ArrayList::new
你没有意识到这并不是推断出来的
() -> new ArrayList<>()
但是
key -> new ArrayList<>(key)
即每个列表都是以 0 到 100000 之间的随机大小创建的。最坏的情况是 50 亿。
关于java - ArrayList::new 中出现不需要的内存不足错误 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59245583/