java学习:java容器——Queue接口分析及应用

java容器——Queue(队列)接口分析及应用

1、概念

队列。Queue继承了Collection接口,是一种常见的数据接口。Queue是一个接口。Dueue继承了Queue接口。LinkedList实现了Queue接口。

Queue:单向队列,遵循先进先出的原则。
Dueue:双向队列,该队列两端的元素既能入队(offer)也能出队(poll),如果将Deque限制为只能从一端入队和出队,则可实现栈的数据结构。对于栈而言,有入栈(push)和出栈(pop),遵循先进后出原则。

2、常用方法

(1)Queue常用方法

增加元素到队尾

add():增加元素到队尾,成功返回true
offer():增加元素到队尾,如果可以在不违反容量限制的情况下立即将指定的元素插入此队列。 当使用容量受限的队列时,此方法通常比add更可取,后者只能通过引发异常而无法插入元素。

获取并移除队列头

remove():获取并移除此队列的头,如果此队列为空,则抛出NoSuchElementException异常
poll():获取并移除此队列的头,如果此队列为空,则返回 null

获取队列首元素,不移除

element():获取队首的元素,但不从队列中移除。如果此队列为空,则将抛出NoSuchElementException异常
peek():获取队首的元素,但不从队列中移除。如果此队列为空,则返回 null
在这里插入图片描述

(2)Dueue常用方法

在这里插入图片描述

3、应用

(1)使用Queue模拟银行存款业务(先进先出)

/**
 * 使用队列模拟银行存款业务(先进先出)
 * @author Linlin Zhao
 *
 */
public class QueueDemo01 {
	public static void main(String[] args) {
		Queue <Request> que =new ArrayDeque<Request>();
		//模拟排队情况
		for(int i=0;i<10;i++){
			final int num=i;//匿名内部类,只能访问final对象。
			que.offer(new Request() {
				@Override
				public void deposit() {
					System.out.println("第"+(num+1)+"个人,办理存款业务,存款额度为: "+Math.round(Math.random()*100000));		
				}
			});	
		}
		dealWith(que);
	}
	//处理业务。先进先出。
	public static void dealWith(Queue<Request> queue){
		Request req=null;
		while(null!=(req=queue.poll())){
			req.deposit();
		}
	}
}

interface Request{
	//存款
	void deposit();
	
}

(2)使用Dueue实现自定义栈

/**
 * 使用队列实现自定义栈
 * 1、弹栈
 * 2、压栈
 * 3、获取头
 * @author Linlin Zhao
 *
 */
public class MyStack01<E> {

	//容器
	private Deque<E> container =new ArrayDeque<E>();
	//容量
	private int cap;
	
	public MyStack01(int cap) {
		super();
		this.cap = cap;
	}
	
	//压栈
	public boolean push(E e){
		if(container.size()+1>cap){
			return false;
		}
		return container.offerLast(e);//加到队尾
	}
	
	//弹栈
	public E pop(){
		return container.pollLast();//移除队尾
	}
	
	//获取
	public E peek(){
		return container.peekLast();//获取队尾
	}

	public int size(){
		return this.container.size();//队列长度
	}

	public static void main(String[] args) {
		
	}
}

发布了57 篇原创文章 · 获赞 13 · 访问量 1121

猜你喜欢

转载自blog.csdn.net/weixin_42924812/article/details/105152133