在Java中使用许多ArraysList时如何减少内存使用

时间:2019-04-07 19:13:53

标签: java memory heap heap-memory

我正在编写一个播放Misere Nim的程序,并且遇到内存问题。我使用ArrayLists来保存可能要做的动作,这导致OutOfMemory异常。如何减少使用ArrayLists时使用的内存?每次跑步后我都应该清理东西吗?

编辑:添加了复制方法 编辑:完整项目可以在https://github.com/DatOneRam/ScienceFair

中找到
do
{
   int tempWin = board.playRound();
   if (tempWin == 0)
      stratWins++;
   else
      randWins++;
}
while (rounds <= 10000);
public int playRound()
    {
        Board board = new Board();
        NimBot strat = new NimBot(board);
        NimBot rand = new NimBot(board);

        do
        {
            strat.makeStrategicMove();
            if (board.hasEnded())
                break;
            rand.makeRandomMove();
        }
        while (!board.hasEnded());

        return board.getPlayer();
    }
public void makeStrategicMove()
    {
        ArrayList<int[]> goodMoves = board.getGoodMoves();
        Random rand = new Random();
        int[] move;
        if (goodMoves.size() != 0)
        {
            move = goodMoves.get(rand.nextInt(goodMoves.size()));
        }
        else
        {
            ArrayList<int[]> simpleMoves = board.getSimpleMoves();
            move = simpleMoves.get(rand.nextInt(simpleMoves.size()));
        }
        board.setPosition(move);
    }
public void makeRandomMove()
    {
        ArrayList<int[]> moves = board.getMoves();
        Random rand = new Random();
        int[] move = moves.get(rand.nextInt(moves.size()));
        board.setPosition(move);
    }
public ArrayList<int[]> getMoves()
    {
        ArrayList<int[]> x = new ArrayList<int[]>();
        int j = 0, i = 1;

        x.add(0, copy(position));
        do
        {
            x.add(i, copy(position));
            if (x.get(i-1)[j] == 0)
                j++;
            x.get(i)[j] = x.get(i-1)[j] - 1;
            i++;
            if (x.get(i-1)[j] == 0)
            {
                j++;
                if (j == 5)
                {
                    break;
                }
            }

        }
        while(x.get(i - 1)[j] != 0);

        for (int r = 0; r < x.size(); r++)
        {
            x.get(r)[4] = toggle(x.get(r)[4]);
        }

        x.remove(0);
        //resize(x);

        return x;
    }
public ArrayList<int[]> getSimpleMoves()
    {
        ArrayList<int[]> x = new ArrayList<int[]>(4);

        for (int i = 0; i < 4; i++)
        {
            x.add(copy(position));
            x.get(i)[i] = position[i] - 1;
            x.get(i)[4] = toggle(x.get(i)[4]);
            if (x.get(i)[i] < 0)
                x.get(i)[i] = 0;
        }

        //resize(x);

        return x;
    }
public int[] copy(int[] y)
    {
        int[] z = new int[y.length];
        for (int i = 0; i < y.length; i++)
            z[i] = y[i];

        return z;

    }

如果在这里放置太多代码,我感到抱歉,我不确定如何缩短代码。

0 个答案:

没有答案