I'm new to Java and I found this linked list implementation down below. In the main method we create a LinkList instance named theLinkedList and using that we call insertFirstLink method 4 times. What InsertFirstLink method does is it creates a Link instance named newLink. When we call insertFirstLink 4 times.
Does this method creates 4 Link instances with the same name (newLink)? How is that possible? We can't create objects with the same name right? What am I missing?What do I need to study to understand this part?
Thank you guys. I understood my problem. After every execution the new link variable is destroyed, but every variable destroyed has a reference and its like a line. We can always go through the line and find the node we want.
public class Link {
public String bookName;
public int millionsSold;
public Link next;
public Link(String bookName, int millionsSold) {
this.bookName = bookName;
this.millionsSold = millionsSold;
}
public static void main(String[] args) {
LinkList theLinkedList = new LinkList();
theLinkedList.insertFirstLink("Don Quixote",500);
theLinkedList.insertFirstLink("A Tale of two cities",200);
theLinkedList.insertFirstLink("The Lord Of The Rings",150);
theLinkedList.insertFirstLink("Harry Potter",1000);
}
}
class LinkList {
public Link firstLink;
LinkList() {
firstLink = null;
}
public boolean isEmpty() {
return(firstLink == null);
}
public void insertFirstLink(String bookName, int millionsSold) {
Link newLink = new Link(bookName, millionsSold);
newLink.next = firstLink;
firstLink = newLink;
}
}