Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何创建一个与原始构造函数(包括所有节点信息)重复的构造函数?_Java - Fatal编程技术网

Java 如何创建一个与原始构造函数(包括所有节点信息)重复的构造函数?

Java 如何创建一个与原始构造函数(包括所有节点信息)重复的构造函数?,java,Java,表示这是TableDeque类(实现Deque)的构造函数,并且类中有更多的节点 public TableDeque() { head = new Node<Customer>(null); tail = new Node<Customer>(null); head.join(tail); size = 0; this.setImage("table"); } 因此,TableDeque(this)必须返回包含所有节点信息的副本原

表示这是
TableDeque
类(实现
Deque
)的构造函数,并且类中有更多的节点

public TableDeque() {
    head = new Node<Customer>(null);
    tail = new Node<Customer>(null);
    head.join(tail);
    size = 0;
    this.setImage("table");
}
因此,
TableDeque(this)
必须返回包含所有节点信息的副本原件,但我不知道如何做到这一点


我自己思考并尝试过这样做,但我仍然坚持这样做:(请给我解决方案。

为您的节点类创建一个副本构造函数,然后:

public TableDeque (TableDeque copy) {
    head = new Node(copy.head);
    tail = new Node(copy.tail);
    size = copy.size;
    setImage(copy.image);
}

如果存在闭合循环,则必须防止节点复制构造函数中出现无限循环(使用集合来跟踪访问的节点)。

如果要进行浅层复制(即在两个位置反射后更改为
头部
尾部
对象),只需将
copy
对象中的字段设置为
this
,如-

public TableDeque (TableDeque copy)
{
    // copy properties from the source TableDeque to the new instance
    this.head = copy.getHead(); //this function returns the `head` property of TableDeque class
    this.tail = copy.getTail(); //this function returns the `tail` property of TableDeque class
    head.join(tail);
    this.size = copy.getSize();  //this function returns the `size` property of TableDeque class
    this.setImage(copy.getImage()); //this function returns the `image` property of TableDeque class

}
我想说的是,总是建议将java中的成员变量保持私有,并为它们公开getter和setter

要创建深度副本(不会反映对
头部
尾部
的更改)-

然后还需要为
节点
类创建一个副本构造函数

public TableDeque (TableDeque copy)
{
    // copy properties from the source TableDeque to the new instance
    this.head = copy.getHead(); //this function returns the `head` property of TableDeque class
    this.tail = copy.getTail(); //this function returns the `tail` property of TableDeque class
    head.join(tail);
    this.size = copy.getSize();  //this function returns the `size` property of TableDeque class
    this.setImage(copy.getImage()); //this function returns the `image` property of TableDeque class

}
public TableDeque (TableDeque copy)
{
    // copy properties from the source TableDeque to the new instance
    this.head = new Node(copy.getHead()); 
    this.tail = new Node(copy.getTail()); 
    head.join(tail);
    this.size = copy.getSize();  
    this.setImage(copy.getImage());

}