Java如何实现queue队列?

时间:2022-06-07 15:19:15

演示如何在雇员结构实现一个队列。

代码块

import java.util.LinkedList;

class GenQueue<E> {

private LinkedList<E> list = new LinkedList<E>();

//将指定元素添加到此列表的结尾
public void enqueue(E item) {
list.addLast(item);
}

//获取并移除此列表的头(第一个元素)
public E dequeue() {
return list.poll();
}

//list.isEmpty()如果列表不包含元素,则返回 true
public boolean hasItems() {
return !list.isEmpty(); //当列表包含元素,返回true
}

//返回此列表的元素数
public int size() {
return list.size();
}

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


public class GenQueueTest {

public static void main(String[] args) {

//定义类GenQueue<Employee>
GenQueue<Employee> empList;

//实例化变量empList
empList = new GenQueue<Employee>();

////定义类GenQueue<HourlyEmployee>
GenQueue<HourlyEmployee> hList;

//实例化变量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);

System.out.println("The employees' names are:");

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



//Employee类
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;
}
}


//钟点工HourlyEmployee类
class HourlyEmployee extends Employee {

//属性
public double hourlyRate;

//有参构造函数
public HourlyEmployee(String last, String first) {
super(last, first);
}
}
运行结果:
The employees' names are:
D T
B G
S F