Defining a Generic Class Type : Generic Class « Generics « Java Tutorial






import java.awt.Point;

class ListItem {
  public ListItem(Object item) {
    this.item = item;
    next = null;
  }

  public String toString() {
    return "ListItem " + item;
  }

  ListItem next;

  Object item;
}

class LinkedList<T> {
  public LinkedList() {
  }

  public LinkedList(T item) {
    if (item != null) {
      current = end = start = new ListItem(item);
    }
  }

  public LinkedList(T[] items) {
    if (items != null) {

      for (int i = 0; i < items.length; i++) {
        addItem(items[i]);
      }
      current = start;
    }
  }

  public void addItem(T item) {
    ListItem newEnd = new ListItem(item);
    if (start == null) {
      start = end = newEnd;
    } else {
      end.next = newEnd;
      end = newEnd;
    }
  }

  public T getFirst() {
    current = start;
    return start == null ? null : start.item;
  }

  public T getNext() {
    if (current != null) {
      current = current.next;
    }
    return current == null ? null : current.item;
  }

  private ListItem start = null;

  private ListItem end = null;

  private ListItem current = null;

  private class ListItem {

    public ListItem(T item) {
      this.item = item;
      next = null;
    }

    public String toString() {
      return "ListItem " + item;
    }

    ListItem next;

    T item;
  }
}

public class MainClass {
  public static void main(String[] a) {

    LinkedList<Point> polyline = new LinkedList<Point>();

    polyline.addItem(new Point(1, 2));

    polyline.addItem(new Point(2, 3));

    Point p = polyline.getFirst();

    System.out.println(p);

  }

}
java.awt.Point[x=1,y=2]








12.6.Generic Class
12.6.1.Defining a Generic Class Type
12.6.2.Using Primitive Type Wrapper Class Types as Arguments
12.6.3.The Run-Time Types of Generic Type Instances
12.6.4.Generic class Stack
12.6.5.Use generic method to test generic Stack
12.6.6.Raw type test for a generic Stack