Java如何实现queue队列?

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

代码块

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值