Java Reference
In-Depth Information
LinkedList defines a single state field, head , that refers to the first Linkable item
in the list. The class also defines a number of methods for adding items to and
removing items from the list. Note that the Linkable interface is nested within the
LinkedList class. While this is a convenient and useful way to define the interface,
it is by no means necessary to nest things in this way. Linkable could just as easily
be defined as an ordinary, top-level interface.
The LinkedList class also defines an inner Test class that, once again, is a stand-
alone program for testing the class. In this example, however, the inner Test class
itself contains an inner class, LinkableInteger . This class implements Linkable ;
instances of it are linked into a list by the test program.
Example 2•8: LinkedList.java
package com.davidflanagan.examples.classes;
/**
* This class implements a linked list that can contain any type of object
* that implements the nested Linkable interface. Note that the methods are
* all synchronized, so that it can safely be used by multiple threads at
* the same time.
**/
public class LinkedList {
/**
* This interface defines the methods required by any object that can be
* linked into a linked list.
**/
public interface Linkable {
public Linkable getNext(); // Returns the next element in the list
public void setNext(Linkable node); // Sets the next element in the list
}
// This class has a default constructor: public LinkedList() {}
/** This is the only field of the class. It holds the head of the list */
Linkable head;
/** Return the first node in the list */
public synchronized Linkable getHead() { return head; }
/** Insert a node at the beginning of the list */
public synchronized void insertAtHead(Linkable node) {
node.setNext(head);
head = node;
}
/** Insert a node at the end of the list */
public synchronized void insertAtTail(Linkable node) {
if (head == null) head = node;
else {
Linkable p, q;
for(p = head; (q = p.getNext()) != null; p = q) /* no body */;
p.setNext(node);
}
}
/** Remove and return the node at the head of the list */
public synchronized Linkable removeFromHead() {
Linkable node = head;
Search WWH ::




Custom Search