栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java、泛型队列

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java、泛型队列

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

本程序实现泛型队列。


package pack2;

import java.util.ArrayList;

public class GenericQueue {
	private ArrayList 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 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 queue2 = new GenericQueue<>();
		queue2.push(1);
		queue2.push(2);
		queue2.push(3);
		queue2.push(4);
		queue2.push(5);
		
		System.out.println(queue2.getQueue());
	}
	
	
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351553.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号