4

我正在尝试创建我的 Board 对象的副本,但它似乎没有实例化。有人能告诉我为什么吗?

    class Board {
       private Board _copyBoard; 
       private int _size;
       public Board (int N) {
          _size = N;
       }
       public Board (Board b) {
            this._copyBoard = b;
       }
       int size() {
            return _size;
       }
    }

当我做:

    Board b = new Board(4);
    Board x = new Board(b);
    System.out.println(x.size()); --> 0 instead of 4.
4

3 回答 3

1

复制构造函数通常应该复制实例变量,并在必要时复制一些深层状态——而不是保留对原始对象的引用。

您的 getter 和方法需要能够在对象自己的状态下,在它自己的变量中进行操作。到处都有某种双路径结构,if语句要么指向你自己的变量,要么指向它复制的原始实例,这是糟糕的设计,非常复杂/低效。

public class Board {
   protected int      size;
   protected Cell[][] grid;
   public Board (int N) {
      this.size = N;
      // for example, create a 2D array.
      this.grid = new Cell[size][size];
   }
   public Board (Board orig) {
       this.size = orig.size();
       // deep-copy the grid.
       this.grid = new Cell[size][];
       for (int i = 0; i < size; i++) {
          grid[i] = Arrays.copyOf( orig.grid[i], size);
      }
   }
   public int size() {return size;}
}

我更喜欢protected私人,以获得更大的多功能性和工程访问权限。

我也不使用字段前缀,而是使用this.. 这种方法非常适用于简单的领域。

对于集合,我在我的字段名后面加上 List 或 Map 或其他;参数命名不带后缀。这使得具有复数的复数操作和方法调用变得清晰。例如,add (List<Customer> customers)将这些添加到 field customerList

于 2013-11-12T01:52:38.307 回答
0

try

 Board b = new Board(4);
 Board x = new Board(b);
System.out.println(x._size); 

class Board {
    public Board _copyBoard; 
    public int _size;
    public Board (int N) {
       this._size = N;
    }
    public Board (Board b) {
         this._size = b._size;
    }
    int size() {
         return _size;
    }
 }

In you code you are not copying the value of size to x, Instead size is getting copied to the instance variable inside X

If you make the variable public, in your code then the below line will print the copied value in your code

System.out.println(x._copyBoard._size); 
于 2013-11-12T01:58:17.160 回答
0
Board b = new Board(4);

这将在其字段中创建一个新板_size = 4

Board x = new Board(b);

这将在其字段中创建一个新板_copyBoard = b

System.out.println(x.size());

这将打印出_size第二块板的字段。您在任何地方都没有链接到_size第一块板的变量。

你可以通过这样做来解决这个问题

    public Board (Board b) {
     this._copyBoard = b;
    }

    int size() {
     if(_copyBoard != null) { 
       return _copyBoard.size(); 
     } else { 
       return _size; 
     }
    }

考虑到所有因素,您可能正在查看数据的实际副本,而不是将这些类视为具有大量 if 语句的字段。

class Board {
    private int _size;
    public Board (int N) {
       _size = N;
    }
    public Board (Board b) {
        _size = b.size();
    }
    int size() {
        return _size;
    }
}
于 2013-11-12T01:46:49.963 回答