Java Collections.asLifoQueue(deque)方法介绍
2015-10-29 15:39
543 查看
Deque是接口,具体继承关系为:Collection-->Queue-->Deque-->LinkedList、ArrayDeque、LinkedBlockingDeque
Collection 是层次集合结构中的根接口。Collection 表示一组对象,这些对象也称为 Collection 的元素。
Queue(队列)接口与List、Set同一级别,都是继承了Collection接口。Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 如果要使用前端而不移出该元素,使用element()或者peek()方法。
Deque(双端队列)接口支持两端插入和移除元素。名称deque 是“double ended queue(双端队列)”的缩写,通常读为“deck”。
实现了Deque的类有LinkedList、ArrayDeque、LinkedBlockingDeque。
LinkedList是大家用的比较多的,LinkedList不仅实现了Deque接口,还实现了List接口。LinkedList内部实现用的是链接链表(它的get()是比较慢的,而ArrayList内部实现用的是数组)。ArrayDeque是Deque接口的数组形式的实现,此类很可能在用作堆栈时快于Stack,在用作队列时快于LinkedList。LinkedBlockingDeque是链表形式实现的阻塞双端队列(当超过队列容量了,put操作会被阻塞,一直等待可用空间)。
此时我们再看Collections.asLifoQueue(deque)方法,它返回得就是一个栈形式的队列。具体见示例代码:
import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; public class CollectionsTest { public static void main(String[] args) { LinkedList<Integer> llist1 = new LinkedList<Integer>(Arrays.asList(2, 4, 6)); System.out.println(llist1); System.out.println(llist1.add(5)); System.out.println(llist1); System.out.println(llist1.offer(9)); System.out.println(llist1); System.out.println(llist1.element()); System.out.println(llist1.peek()); System.out.println(llist1); System.out.println(llist1.poll()); System.out.println(llist1); System.out.println("-------------------------"); LinkedList<Integer> llist2 = new LinkedList<Integer>(Arrays.asList(2, 4, 6)); Queue q = Collections.asLifoQueue(llist2); System.out.println(q); System.out.println(q.add(5)); System.out.println(q); System.out.println(q.offer(9)); System.out.println(q); System.out.println(q.element()); System.out.println(q.peek()); System.out.println(q); System.out.println(q.poll()); System.out.println(q); } }
运行结果截图:
相关文章推荐
- UILabel高度的自适应以及UITableViewCell的高度自适应
- easyui tree节点取消选择方法
- Kendo UI - Class 基类定义
- iOS 如何解决UITableView刷新卡顿现象
- iOS_ UIScrollview_无限循环
- 日常问题记录--JSP页面中通过<s:property value="#parameters.userName[0]>获取URL参数中文时为乱码的解决办法
- warning: push.default is unset; its implicit value has changed in Git 2.0 from 'matching' to 'simple
- QueryRunner的使用
- 随机生成36位的UUID
- 【Mockplus教程】添加
- 【Mockplus教程】删除
- 【Mockplus教程】复制/粘贴/克隆
- easyui datebox 清空值或添加自定义按钮
- 使用Auto-Scaling服务在Bluemix平台构建可自动伸缩的应用
- 如何布局包含Image和Title的UIButton
- How to use For loop in CruiseControl.net
- 转载: buildroot编译环境
- Could not build module ‘libxmlSimu'
- uIP编译时配置选项
- iOS UICollectionViewController基本使用方法和简单的相册实现