I am studying the linked lists,and I'm having a little problem understanding references and pointers in Java (and also have some questions for which I can't find answer on the internet.) Namely,I have a class LinkedList that uses class Node like this:
public class LinkedList { public Node head; public LinkedList(int data) { head = new Node(data); } } and this is my Node class:
public class Node { public int data; public Node next; public Node(int data2) { data = data2; } } I also have method toStringLL() inside LinkedList which looks like:
public void toStringLL() { LinkedList l=this; while(l.head.next != null) { System.out.print(l.head.data+"->"); l.head = l.head.next; } System.out.print(l.head.data); System.out.println(""); } I don't understand why this toStringLL() changes my head of linked list,when I am iterating through it with l.head=l.head.next? Shouldn't my head stay the same?I thought that when I write LinkedList l=this,I can freely iterate through l,without affecting this(or am I wrong?) Now when I use Node n=this.head instead of LinkedList l=this,it works,but I have difficulty figuring out why that works and the previous doesn't.. Can someone explain to me the difference between these two?
LinkedList l = this;you are not making a copy of the list, you are just creating another variable that refers to the sameLinkedListobject. Variables in Java (of non-primitive types) are references, not objects themselves.