Using Primitive Type Wrapper Class Types as Arguments : Generic Class « Generics « Java Tutorial






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[] args) {
    LinkedList<Double> temperatures = new LinkedList<Double>();

    // Insert 6 temperature values 0 to 25 degress Centigrade
    for (int i = 0; i < 6; i++) {
      temperatures.addItem(25.0 * Math.random());
    }

    System.out.printf("%.2f degrees Fahrenheit%n", toFahrenheit(temperatures.getFirst()));
    Double value = null;
    while ((value = temperatures.getNext()) != null) {
      System.out.printf("%.2f degrees Fahrenheit%n", toFahrenheit(value));
    }
  }

  // Convert Centigrade to Fahrenheit
  public static double toFahrenheit(double temperature) {
    return 1.8 * temperature + 32.0;
  }
}
69.27 degrees Fahrenheit
51.55 degrees Fahrenheit
59.97 degrees Fahrenheit
35.82 degrees Fahrenheit
41.28 degrees Fahrenheit
37.99 degrees Fahrenheit








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