1. Linked Objects
Review of references
Recall that object types are references, thus you can have several classes such as:
class A { B next; } class B{ C next; } class C{ }
In the above example, "A" objects by default have their next field set to "null". Similarly, "B" objects by default have their next field also set to null. Thus, creating an A does not automatically create a B nor a C. You would need the following statements in a function to connect all three together:
A a = new A(); a.next = new B(); //set the a.next reference to memory location of new object a.next.next = new C(); //set the next reference in the "B" object a.next, set that to new C
The Linked List Node Class
Because fields are merely references, a class can reference an instance of itself. Later, we will connect multiple objects with these links. We call each of these objects, "Nodes":
class Node { int data; // Some optional information associated with each object Node next; // a reference to another node }
Linking several nodes
Once we have a node class with a "next" reference, you can create several nodes and connect them together:
//in some function somewhere: Node a = new Node(); a.data = 10; Node b = new Node(); b.data = 20; Node c = new Node(); c.data = 30; //Now we have 3 nodes, and we can connect them: a.next = b; b.next = c; System.out.println(a.data); //prints 10 System.out.println(a.next.data); //prints 20 System.out.println(a.next.next.data); //prints 30 System.out.println(a.next.next.next); //null //Note that if you tried a.next.next.next.data, // ... you would get a NullPointerException
A generic Node class
We call objects linked linearly in a line a "Linked List". Often, we want to story arbitrary information with each node in the list. Although in the above example we had the field "int data", we may want to store other types. Thus, often the Node object is generic:
class Node<T> { //T is the generic ("templated") type T data; Node<T> next; //You need to re-specify the generic... // when referencing the next node }
Doubly linked lists
In the previous example, every object references the next object in the list. This is sometimes called a singly linked list. However, if we have each node also reference the previous object, this is called a doubly linked list. Here's an example doubly linked list node class:
class Node<T> { T data; Node<T> previous; Node<T> next; //Additionally here are some useful constructors and methods: Node(T d) { data = d; } T getData() { return data; } void setData(T d) { data = d; } Node<T> getNext() { return next; } Node<T> getPrevious() { return previous; } void setNext(Node<T> n) { next = n; } void setPrevious(Node<T> p) { previous = p; } }