Java方法返回同一个类的对象

时间:2017-08-07 02:51:11

标签: java

我的以下代码出现问题:

public class Board {
    private int[][] blocks;
    private  int dim;
    private int hDistance;
    private int mDistance;
    private int indexRow;//row of the empty block;
    private int indexColumn;//column of the empty block;

    public Board(int[][] blocks)                                             
    {       
       dim = blocks.length;
       this.blocks = new int[dim][dim];
       this.blocks = blocks;
       mDistance = manhattan();
       hDistance = hamming();   
    }

    public Board twin()                    
    {
       Board twinBoard = this;

       if(indexRow!=0)
       {
          exch(twinBoard.blocks, 0, 0, 0, 1);//swap(twinBoard.blocks[0][0] with twinBoard.blocks[0][1] 
       }
       else
       {
          exch(twinBoard.blocks, 1, 0, 1, 1);//swap(twinBoard.blocks[1][0] with twinBoard.blocks[1][1] 
       }
       return twinBoard;        
    }
    private void exch(int[][] blocks, int i1, int j1, int i2, int j2)
    {
       int temp;
       temp = blocks[i1][j1];
       blocks[i1][j1] = blocks[i2][j2];
       blocks[i2][j2] = temp;
    }
    public static void main(String[] args)
    {

       int[][] a = {
                {2,0,4},
                {1,5,7},
                {3,6,8}
                };

       Board board1 = new Board(a);
       Board board2 = board1.twin();
    }
}

打印出board1.blocks我得到了:

2,0,4

5,1,7

-3,6,8-

而不是

2,0,4

-1,5,7-

-3,6,8-

board1.blocks是如何交换的?我怎样才能board2.block交换,board1.block保持不变?

1 个答案:

答案 0 :(得分:0)

问题在于这一行:

Board twinBoard = this;

您的代码的“双胞胎”是不同的主板:它与this是同一个主板,因此对twinBoard所做的任何更改都会反映在{{1}同样。

要解决此问题,请定义用于复制电路板的新构造函数:

this

在此构造函数中,您需要复制private Board(Board other) { ... } ,并将boardhDistance和其他字段设置为mDistance板中的值。现在你可以使用这个构造函数来制作一块双板:

other