user2089523
user2089523

Reputation: 63

How do Nodes work in java?

Ok, I have a class called CarNode:

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

and a copy constructor:

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;
        }
    }
}

What I don't understand is how element can get the value of another car node through element.getNode(), but you need to write node.setNode() and node.setCar() for node... I am confused...

Upvotes: 1

Views: 7170

Answers (1)

arcy
arcy

Reputation: 13103

CarNode has a variable, node, that is also a CarNode; this means a CarNode object can contain a reference to another CarNode object. element is a variable that contains a reference to a CarNode. The code element = element.getNode() assigns the reference within the element object to the element reference itself (or null, if the node within element is null).

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.

Upvotes: 1

Related Questions