java - ArrayList::new 中不需要的内存不足错误 - 为什么?
问题描述
我只有50000个对象时出现内存不足错误。
我检查了computeIfAbsent
实现,但不幸的是没有发现任何特殊的东西。
我的机器配置是16 GB
ram 和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 亿。
推荐阅读
- php - 如果特定键不存在,如何删除数组数组?
- c - 如何使用 scanf 将值分配给其数组是动态创建的 Struct 类型变量的成员
- python - Python隐藏/禁用警告
- c# - 在字段 Entity Framework Core 中设置默认值
- python - 如何使用正则表达式结果列表在 Pandas 中生成数据框(稍后导出为 CSV)?
- reactjs - 映射父级时更新嵌套数组内的状态
- python - 如何使用列表推导来存储列表的嵌套列表
- pandas - 使用 group by 划分两列
- vba - 在什么时候我可以运行 RecordCount 来给我正确的记录数
- php - Laravel 7.6 - 路线[登录]未定义