[英]Why does this code throw Exception in thread "main" java.lang.OutOfMemoryError: Java heap space?
import java.util.HashMap;
import java.util.HashSet;
public class ComputeIfAbsentWithHashSetNew {
public static void main(String[] args) {
var map = new HashMap<Integer, HashSet<Integer>>();
var data = new int[][]{{305589003, 4136}, {305589004, 4139}};
for (var entry : data) {
int x = entry[0];
int y = entry[1];
// map.computeIfAbsent(x, _x -> new HashSet<>()).add(y); // ----- line 1
var k = map.computeIfAbsent(x, HashSet::new); // ----- line 2
k.add(y);
}
}
}
Above code throws at jdk 17、 18、 19:以上代码在jdk 17、18、19抛出:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.HashMap.resize(HashMap.java:702)
at java.base/java.util.HashMap.putVal(HashMap.java:627)
at java.base/java.util.HashMap.put(HashMap.java:610)
at java.base/java.util.HashSet.add(HashSet.java:221)
at _explore.ComputeIfAbsentWithHashSetNew.main(ComputeIfAbsentWithHashSetNew.java:15)
When debug, I see the newCap
in Hashmap::resize()
is very large, I don't know why. debug的时候看到newCap
Hashmap::resize()
里面的newCap很大,不知道为什么。 I thought both the lines do same thing previously.我以前认为两条线都做同样的事情。
When I replace line 2 with line 1 in code, it runs successfully.当我用代码中的第 1 行替换第 2行时,它运行成功。
HashSet::new
is a method reference pointing to new HashSet(initialCapacity)
. HashSet::new
是指向new HashSet(initialCapacity)
的方法引用。 See the java-doc of HashSet .请参阅HashSet的 java-doc。
So, it creates a bigger HashSet
s than you expect, because it takes your x
variable as parameter.因此,它创建了一个比您预期更大的HashSet
s,因为它将您的x
变量作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.