1

好的,我有一个名为 CarNode 的类:

public class CarNode {
    private Car car;
    private CarNode node;
}

和一个复制构造函数:

public CarList(CarList list) {
    CarNode element = list.head;
    CarNode node = new CarNode();
    this.head = node;

    while(element != null) {
        node.setCar(element.getCar());
        element = element.getNode();

        if(element != null) {
            node.setNode(new CarNode());
            node = element;
        }
    }
}

我不明白的是element如何通过element.getNode()获取另一个汽车节点的值,但是您需要为节点编写node.setNode()和node.setCar() ...我很困惑.. .

4

1 回答 1

1

CarNode 有一个变量 node,它也是一个 CarNode;这意味着 CarNode 对象可以包含对另一个 CarNode 对象的引用。 element是一个包含对 CarNode 的引用的变量。代码element = element.getNode()将元素对象内的引用分配给元素引用本身(如果元素内的节点为空,则为空)。

In order to set a value on the node element within a CarNode, you call setNode(elementReference), giving rise to the syntax node.setNode(new CarNode());.

Does this answer your question? I realize it may be hard to explain what you want to ask, but in fact we don't have a very clear question yet.

--- addendum

I'll try to answer your comments here, since more comments are limited in space and formatting.

I think you're confusing the "object" with the "object reference". You can think of the object as a block of memory somewhere in the program, and the object reference as the address of that block. Consider the statement:

CarNode myCar = new CarNode();

You have created a block of memory with new CarNode(), and myCar now refers to it. If you were to now execute the statement CarNode secondCar = myCar;, you would have a second reference to the same object, i.e., to the same block of memory. Any changes made to the object/block of memory would be reflected in both myCar and secondCar.

Your "copy constructor" as you call it, is confusing to me also. I'm not sure what you're trying to do. Usually a copy constructor creates one or more objects that contain the same data as an original object or set of objects. First of all, if the original list pointer is null, this will throw a NullPointerException on the first line. You create a first node and set it to be the head, that's fine, but the node = element; statement is just wrong. node holds a node you are creating to put in your new list, and element holds an element from the original list.

于 2013-03-31T02:12:40.837 回答