A Generic Queue Class Using Wildcard Type Parameters - Java Object Oriented Design

Java examples for Object Oriented Design:Generic Class

Description

A Generic Queue Class Using Wildcard Type Parameters

Demo Code

import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    GenQueue<Employee> empList;/*from ww  w  .  j a va  2s.com*/
    empList = new GenQueue<Employee>();

    GenQueue<HourlyEmployee> hlist;
    hlist = new GenQueue<HourlyEmployee>();
    hlist.enqueue(new HourlyEmployee("T", "D"));
    hlist.enqueue(new HourlyEmployee("G", "B"));
    hlist.enqueue(new HourlyEmployee("F", "S"));

    empList.addItems(hlist);

    while (empList.hasItems()) {
      Employee emp = empList.dequeue();
      System.out.println(emp.firstName + " " + emp.lastName);
    }
  }
}

class GenQueue<E> {
  private LinkedList<E> list = new LinkedList<E>();

  public void enqueue(E item) {
    list.addLast(item);
  }

  public E dequeue() {
    return list.poll();
  }

  public boolean hasItems() {
    return !list.isEmpty();
  }

  public int size() {
    return list.size();
  }

  public void addItems(GenQueue<? extends E> q) {
    while (q.hasItems())
      list.addLast(q.dequeue());
  }
}

class Employee {
  public String lastName;
  public String firstName;

  public Employee() {
  }

  public Employee(String last, String first) {
    this.lastName = last;
    this.firstName = first;
  }

  public String toString() {
    return firstName + " " + lastName;
  }
}

class HourlyEmployee extends Employee {
  public double hourlyRate;

  public HourlyEmployee(String last, String first) {
    super(last, first);
  }

}

Related Tutorials