I'm trying to pick up Java again using the book Data Structures & Algorithms in Java, in pg 191, the book implements link list. The code first builds a link class, a link list class and a client class linkapp.
public class Link {
public int data;
public link next;
public Link (int newdata){
data=newdata;
}
}
public class Linklist {
public Link first;
public void insertFirst(int data){
Link newlink=new Link (data);
newlink.next=first;
first=newlink;
}
public boolean isEmpty(){ return (first==null); }
public void displaylist(){
if (!isEmpty()){
Link current=first;
while(current!=null){
System.out.print(current.data);
current=current.next;}
}
}
}
public class LinklistApp {
public static void main(String[] args) {
Linkedlist linkList = new Linkedlist();
linkList.insertFirst(3);
linkList.insertFirst(4);
linkList.insertFirst(5);
linkList.displaylist();
}
}
But I don't understand why the link object created locally in the insertFirst method inside linklist class can be accessed by displaylist method. Local variables will disappear when the method exits because they're just intermediate result. So how did displaylist method still have access to those link objects?
The value of the newlink
variable in insertFirst
is copied into the instance variable here:
first=newlink;
Then in displayLink
, the value of first
is copied back into a local variable:
link current=first;
It's important to distinguish between variables and their values - and also between references and objects. The values of all these link
variables are only references.
(As an aside, is this example straight out of the book? If so, I'm concerned at the use of unconventional names like link
instead of Link
for a class, and newlink
instead of newLink
as a variable.)
See more on this question at Stackoverflow