提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用通配符类型参数的通用队列类
import java.util.LinkedList; public class Main { public static void main(String[] args) { /* 来 自* n o w j a v a . c o m */ GenQueue<Employee> empList; 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();/**来自 nowjava.com**/ 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; }