Jok*_*ker 10 java collections java-8
我只有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");
}
Run Code Online (Sandbox Code Playgroud)
我的 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;
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮助我理解这种行为。
Mic*_*ael 17
错误的部分是这样的:
ArrayList::new
Run Code Online (Sandbox Code Playgroud)
你没有意识到的是,这不是推断出来的
() -> new ArrayList<>()
Run Code Online (Sandbox Code Playgroud)
但要
key -> new ArrayList<>(key)
Run Code Online (Sandbox Code Playgroud)
即每个列表都是用从 0 到 100000 的随机大小创建的。最坏的情况是 50 亿。
| 归档时间: |
|
| 查看次数: |
263 次 |
| 最近记录: |