gpt4 book ai didi

java - Eclipse 中 10000x10000 int 数组出现 OutOfMemoryError

转载 作者:行者123 更新时间:2023-12-01 07:39:31 24 4
gpt4 key购买 nike

我编写了一个小程序来检查按行或列循环遍历二维数组的时间,因为我记得对于大型数据集,一种方法要快得多,但我不记得哪种方法。不过,当我运行程序时,我遇到了一个有趣的错误。

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at testing.ForLoopTest.main(ForLoopTest.java:10)

现在,在我的测试中,我使用 int[10000][10000] 在 Eclipse 中使用默认堆设置运行。我知道我可以增加堆大小,但我的直觉告诉我,这应该运行得很好,而不需要我这样做。这是正常的吗?我的代码中是否有一些我没有看到的愚蠢内容?

这是我的代码

public static void main(String[] args){
final int arrSize = 10000;
long start = 0;
long rowFirstTime = 0;
long colFirstTime = 0;
int[][] arr = new int[arrSize][arrSize];

start = System.currentTimeMillis();
for(int x = 0; x < arrSize; x++){
for(int y = 0; y < arrSize; y++){
arr[x][y] = -1;
}
}
rowFirstTime = System.currentTimeMillis() - start;
start = System.currentTimeMillis();
for(int y = 0; y < arrSize; y++){
for(int x = 0; x < arrSize; x++){
arr[x][y] = 0;
}
}
colFirstTime = System.currentTimeMillis() - start;
System.out.println("row time is " + rowFirstTime);
System.out.println("col time is " + colFirstTime);
}

错误发生在数组初始化时,它没有进入 for 循环。

谢谢,兹德克斯

最佳答案

您正尝试为 10 000 个长度为 10 000 的数组分配内存。这需要大量内存(原始计算约为 400 MiB),而这些内存在您的 JVM 中不可用。这会导致您的 OutOfMemoryError

尝试增加执行参数中分配给 JVM 的内存量。您正在查看类似 -Xmx 参数的内容。尝试为其指定大于 400 MiB 的值。我认为您也许可以在 Eclipse 的项目属性中更改此值。

关于java - Eclipse 中 10000x10000 int 数组出现 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7029463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com