i just encountered a strange thing with object reference as i was creating my own linked list,
The main class
public class WordLinkedListSampleProgram { public static void main(String[] args) { WordLinkedList nL = new WordLinkedList(); nL.addValue("A"); nL.addValue("B"); nL.reversedLink(); } }
The WordLinkedList class
public class WordLinkedList { private Node start; private Node next; private Node last; private int listSize; public void addValue(String val) { if (listSize == 0) { start = new Node(val); next = start; start.setNext(next); } else { next.setNext(new Node(val)); last = next.getNext(); next = last; last.setNext(null); } listSize++; } public void reversedLink() { Node tempStart, tempNext; tempStart = last; tempNext = tempStart; // tempStart.setNext(tempNext); // i was expecting this part should throw a null pointer exception, // but if the above statement tempStart.setNext(tempNext); is UNCOMMENTED // this statement doesnt throw any exception even with more .getValue() consecutive calls System.out.println(start.getNext().getNext().getValue()); } }
The Node class
public class Node { private Node nextNode; private String value; public Node(String val) { value = val; } public Node getNext() { return nextNode; } public void setNext(Node n) { nextNode = n; } public String getValue() { return value; } }
base on what i know so far is, the local 'tempStart' affects the reference of the data member 'last'?
what i know is, this kind of reference control is only possible with java arrays
how come it happens with data fields and objects?
the data member 'last''s references should not be affected when i pass it in another variable.. how come in my case it does?
am i missing something?
please correct and enlighten me, thank you in advance. any help would be greatly appreciated