为什么会产生堆OutOfMemory错误?

时间:2016-12-13 20:17:22

标签: java

for(int i = 0; i < colorOrder.size(); i++)
    {
        String colour = "";
        colour = gui.getUserInputElement(i);
        userColourInput.add(colour);
    }

基本上我创造了一个&#34;西蒙说&#34;游戏,我试图将数据从一个类中保存的arrayList移动​​到另一个类中保存的arrayList中,以便我可以操作数据。 colorOrder和userColourInput是arrayLists,getUserInputElement()方法如下:

public String getUserInputElement(int index)
    {
        return userInput.get(index);
    }

我收到的错误消息是:

java.lang.OutOfMemoryError:Java堆空间

at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at Game.gameLoop(Game.java:87)
at Game.<init>(Game.java:23)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at bluej.runtime.ExecServer$3.run(ExecServer.java:746)

GameLoop如下,不确定哪个部分是必需的,所以如果我发布整个内容,希望它不会太不方便。

public void gameLoop()
{
    while(true)
    {
        String input = "";
        boolean userInputFull = false;
        int inputSize = 0;

        if(orderPulled == false)
        {
            getColorOrder();
            System.out.println("colorOrder set to order ArrayList");
            userClicks = colorOrder.size();
            System.out.println("User clicks set to " + userClicks);
            orderPulled = true;

        }


        if(flashed == false)
        {
            pause(2000); //taking this out of here and putting in init or in this loop
        }                //causes a freeze, why?



        if(flashed == false)
        {
            for(int i = 0; i < colorOrder.size(); i++)
            {
                gui.flashButton(colorOrder.get(i));
                System.out.println("Flashing " + colorOrder.get(i));
                pause(500);
            }
            gui.changeInstructionCopy();
            flashed = true;
            gui.enableButtons();
            System.out.println("colorOrder size: " + colorOrder.size());

        }

        inputSize = gui.getUserInputSize();

        if(inputSize == colorOrder.size())
        {
            gui.disableButtons();

            for(int i = 0; i < colorOrder.size(); i++)
            {
                String colour = "";
                colour = gui.getUserInputElement(i);
                userColourInput.add(colour);
            }

        }
        else
        {
            gui.enableButtons();
            gui.printUserInputArray();
        }







    }
}

1 个答案:

答案 0 :(得分:0)

最有可能的是,您永远不会清除userColourInput:您在while (true)循环中不断添加和添加元素,直到内存不足为止。