// File: TestGeneric.java // // Author: Rahul Simha // Created: Sept 2008 // // A linked list in Java - v5, with templates. // A node that contains any "Object" class ListItem { E data = null; // Note: the type is declared as E ListItem next = null; // Constructor: notice the type - same identifier as the class generic. public ListItem (E obj) { data = obj; next = null; } // Accessor: notice the return type. public E getData () { return data; } } // Linked list class - also a dynamic class. class LinkedList { ListItem front = null; ListItem rear = null; int numItems = 0; // Current number of items. // Could this class use a constructor? // Instance method to add a data item. public void addData (E obj) { if (front == null) { front = new ListItem (obj); rear = front; } else { rear.next = new ListItem (obj); rear = rear.next; } numItems++; } public void printList () { ListItem listPtr = front; System.out.println ("List: (" + numItems + " items)"); int i = 1; while (listPtr != null) { System.out.println ("Item# " + i + ": " + listPtr.getData()); i++; listPtr = listPtr.next; } } } // End of class "LinkedList" // An object to use in the list: class Person { String name; String ssn; // Constructor. public Person (String nameInit, String ssnInit) { name = nameInit; ssn = ssnInit; } // Override toString() public String toString () { return "Person: name=" + name + ", ssn=" + ssn; } } // End of class "Person" // Test class. class TestGeneric { public static void main (String[] argv) { // Notice how the actual type is provided: LinkedList L = new LinkedList (); // Create a Person instances and add it to list. L.addData (new Person ("Terminator", "444-43-4343")); L.addData (new Person ("Rambo", "555-54-5454")); L.addData (new Person ("James Bond", "666-65-6565")); L.addData (new Person ("Bruce Lee", "777-76-7676")); // Print contents. L.printList(); } } // End of class "TestGeneric"