gpt4 book ai didi

java - 为什么我在 java 中遇到 OutOfMemoryError 错误?

转载 作者:行者123 更新时间:2023-12-02 00:39:20 24 4
gpt4 key购买 nike

我正在解决投影仪问题,并且遇到了 OutOfMemoryError
我不明白为什么,因为我的代码工作得很好(至少在我的新手看来:P)。
一切正常,直到循环达到 113383
如果有人可以帮助我调试这个,我将不胜感激,因为我根本不明白为什么它会失败。

我的代码

import java.util.Map;
import java.util.HashMap;
import java.util.Stack;

/*
* The following iterative sequence is defined for the set of positive integers:
n = n/2 (n is even)
n = 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 40 20 10 5 16 8 4 2 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1. Which starting number, under one million,
produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
*/
public class Problem14 {

static Map<Integer, Integer> map = new HashMap<Integer, Integer>();
final static int NUMBER = 1000000;

public static void main(String[] args) {

long start = System.currentTimeMillis();
map.put(1, 1);
for (int loop = 2; loop < NUMBER; loop++) {
compute(loop);
//System.out.println(map);
System.out.println(loop);
}
long end = System.currentTimeMillis();
System.out.println("Time: " + ((end - start) / 1000.) + " seconds" );
}

private static void compute(int currentNumber) {
Stack<Integer> temp = new Stack<Integer>();
/**
* checks to see if current value is already
* part of the map. if it isn't, add to temporary
* stack. also if current value exceeds 1 million,
* don't check map or add to stack.
*/
while (!map.containsKey(currentNumber)){
temp.add(currentNumber);
currentNumber = realCompute(currentNumber);
while (currentNumber > NUMBER){
currentNumber = realCompute(currentNumber);
}
}
System.out.println(temp);
/**
* adds members of the temporary stack to the map
* based on when they were placed in the stack
*/
int initial = map.get(currentNumber) + 1;
int size = temp.size();

for (int loop = 1; loop <= size; loop++){
map.put(temp.pop(), initial);
initial++;
//key is the top of stack
//value is initially 1 greater than the current number that was
//found at the map, then incremented by 1 afterwards;
}
}

private static int realCompute(int currentNumber) {

if (currentNumber % 2 == 0) {
currentNumber /= 2;
} else {
currentNumber = (currentNumber * 3) + 1;
}
return currentNumber;
}
}

最佳答案

在我看来,这正是错误所说的:你的内存不足。使用 -Xmx 增加堆大小(例如java -Xmx512m)。

如果您想减少内存占用,请查看 GNU Trove更紧凑(更快)地实现原始映射(而不是使用 HashMap<Integer,Integer> )。

关于java - 为什么我在 java 中遇到 OutOfMemoryError 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6825146/

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