Почему я получаю OutOfMemoryError в Java? - PullRequest
0 голосов
/ 26 июля 2011

Я работаю над проблемой проектора, и я столкнулся с 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;
    }
}

Ответы [ 4 ]

2 голосов
/ 26 июля 2011

Мне кажется, что именно это и говорит ошибка: вам не хватает памяти. Увеличьте размер кучи с помощью -Xmx (например, java -Xmx512m).

Если вы хотите уменьшить объем памяти, посмотрите на GNU Trove для более компактной (и более быстрой) реализации примитивных карт (вместо использования HashMap<Integer,Integer>).

1 голос
/ 27 сентября 2011

У меня точно такая же проблема, как и у вас ... Проблема на самом деле заключается в "Stack temp", и изменить его на Long было бы хорошо.Это простое переполнение.

0 голосов
/ 26 июля 2011

Вы должны определить HashMap как: map = new HashMap (NUMBER).

Вы знаете, «Entry [] table» - это структура данных карты , автозаполнение.

причина начальной емкости: 1, а не копия массива. 2, бегите быстрее.

0 голосов
/ 26 июля 2011

Какая ошибка OutOfMemory?Куча, PermGen ..?Вероятно, нужно увеличить размер кучи или размер permgen.

...