Я пытаюсь понять реализацию LinkedList на основе ссылочной ссылки http://www.java2novice.com/data-structures-in-java/linked-list/singly-linked-list/.
Там они создали класс Node, как показано ниже:
class Node<T> implements Comparable<T> {
private T value;
private Node<T> nextRef;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNextRef() {
return nextRef;
}
public void setNextRef(Node<T> ref) {
this.nextRef = ref;
}
@Override
public int compareTo(T arg) {
if(arg == this.value){
return 0;
} else {
return 1;
}
}
}
И реализовали Единый связанный список какниже:
public class SinglyLinkedListImpl<T> {
private Node<T> head;
private Node<T> tail;
public void add(T element){
Node<T> nd = new Node<T>();
nd.setValue(element);
System.out.println("Adding: "+element);
/**
* check if the list is empty
*/
if(head == null){
//since there is only one element, both head and
//tail points to the same object.
head = nd;
tail = nd;
} else {
//set current tail next link to new node
//When this line gets executed, it's also updating head variable's nextRef object. How that works?!?!
tail.setNextRef(nd);
//set tail as newly created node
tail = nd;
}
}
...
...
}
Я не могу понять, когда выполняется нижняя строка, он также обновляет объект nextRef переменной заголовка.Как это работает?!?!
tail.setNextRef (nd);
Я попытался отладить и увидеть значения объектов и заметил, что в переменной head только онипродолжайте добавлять данные элементы с nextRef
.Но как это head.nextRef
get обновляется на tail.setNextRef(nd)
шаге !!!
Может быть, это глупый вопрос, но он сошел с ума от того, как это происходит!(