Java、泛型队列

队列:先进先出的线性表,元素间具有一对一的关系。

本程序实现泛型队列。


package pack2;

import java.util.ArrayList;

public class GenericQueue<T> {
	private ArrayList<T> list;

	public GenericQueue() {
		super();
		list = new ArrayList<>();
	}

	public GenericQueue(int capacity) {
		super();
		try {    //如果capacity小于0,抛出并捕获异常(抛出来自new ArrayList<>(capacity))
			list = new ArrayList<>(capacity);
			
		}catch(IllegalArgumentException ex) {
			System.out.println(ex.getMessage());
			System.exit(1);
		}
	}
	
	public void push(T o) {
		list.add(o);
	}
	
	public T pop() {
		if(isEmpty()) {
			System.out.println("This is an empty queue, so cannot pop");
			System.exit(1);
		}
		
		T temp = list.remove(0);
		return temp;
	}
	
	public T peak() {
		if(isEmpty()) {
			System.out.println("This is an empty queue, so cannot peak");
			System.exit(2);
		}
		
		return list.get(0);
	}
	
	public int getSize() {
		list.trimToSize();	//调用trimToSize()方法压缩大小为实际大小
		
		return list.size();
	}
	
	public String getQueue() {
		return "Queue: "+list.toString();
	}
	
	public boolean isEmpty() {
		return getSize() == 0;
	}
	
}

测试程序如下:

package pack2;

public class TestGeneric {

	public static void main(String[] args) {
		GenericQueue<String> queue1 = new GenericQueue<>();
		queue1.push("China");
		queue1.push("is");
		queue1.push("a");
		queue1.push("country");
		System.out.println(queue1.getQueue());
		
		System.out.println("The peek of queue1 is "+queue1.peek());
		queue1.pop();
		System.out.println("The new peek of queue1 is "+queue1.peek());
		System.out.println("The value of popping is "+queue1.pop());
		System.out.println(queue1.getQueue());
		System.out.println("The current size of the queue1 is "+queue1.getSize());
		
		GenericQueue<Integer> queue2 = new GenericQueue<>();
		queue2.push(1);
		queue2.push(2);
		queue2.push(3);
		queue2.push(4);
		queue2.push(5);
		
		System.out.println(queue2.getQueue());
	}
	
	
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值