Question

First off, I need an explanation rather than a solution. As you see from the code, I am trying to insert a MovieNode into a MovieList. And the method is in the MovieList class. "list" is where I keep my MovieNodes.

public void insert(Movie movie, int index)
{
    MovieNode node = new MovieNode(movie);
    MovieNode element;
    MovieNode current = list;

    while(current.previous != null)
        current = current.previous;
    element = current; // first node in the list

    for(int n = 1; n < index; n++)
        element = element.next; // determines where to put new node

    node.next = element;
    element.previous.next = node;

}

The method above seems working. However when I change this line

element.previous.next = node;

with this one;

element = node;

There is no change in the linkedlist after insertion. It seems to me that element.previous.next is just the same thing as element itself since when we replace element with node, we also change the successor of the node that comes before the element in the list. And we point that successor to our new element which is node. I am new to the subject so I am sorry for the mistakes that I may have made.

Était-ce utile?

La solution 2

element is a reference to a MovieNode, element.previous.next is another reference to the same MovieNode. The difference between these two is that element is a temporary reference within the scope of your function ; however the element.previous.next is a reference held by the element.previous node which is defined outside this scope.

It is important to remember that in Java saying a = b where a and b are objects, means that a and b refer to the same object. If you modify a, b will also change.

This is why you copied the MovieNode at the beginning of the function : to effectively copy the node instead of referring to it. The rest of the affectations just manipulate the previous and next references and do not handle the actual objects.

Autres conseils

There is a difference:

element.previous.next = node;

will make the previous' element next field point to node, i.e. it will change the previous element.

element = node;

will just assign the local variable element with the (new) node - so it is close to a no-op.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top