java.util.Queue(队列)的简单使用
2024-10-12 23:46:50
import java.util.LinkedList;
import java.util.Queue; import org.junit.Before;
import org.junit.Test; /**
* 队列测试:实现类使用LinkedList
*
* Queue也有很多其他的实现类,比如java.util.concurrent.LinkedBlockingQueue。
* LinkedBlockingQueue是一个阻塞的线程安全的队列,底层实现也是使用链式结构。
*/
public class TestQuene { // 定义一个队列
Queue<String> queue; @Before
public void before() {
// 实例化队列变量
queue = new LinkedList<String>(); // add方法向队列中添加元素,返回布尔值,add方法添加失败时会抛异常,不推荐使用
// queue.add("1");
// queue.add("2");
// queue.add("3");
// queue.add("4");
// queue.add("5"); // offer方法向队列中添加元素,返回布尔值
queue.offer("a");
queue.offer("b");
queue.offer("c");
queue.offer("d");
queue.offer("e"); } // poll方法移除队列首个元素并返回,若队列为空,返回null
@Test
public void test1() {
// 弹出元素
String pollEle = queue.poll(); // 先进先出,弹出了a
System.out.println(pollEle); // a
System.out.println(queue); // [b, c, d, e]
} // remove方法移除首个元素并返回,若队列为空,会抛出异常:NoSuchElementException,不推荐使用
@Test
public void test2() {
// 弹出元素
String remove = queue.remove(); // 先进先出,弹出了a
System.out.println(remove); // a
System.out.println(queue); // [b, c, d, e]
} // peek方法返回队列首个元素,但不移除,若队列为空,返回null
@Test
public void test3() {
// 查看首个元素
String peek = queue.peek(); // 首个元素是a,最先加入
System.out.println(peek); // a
System.out.println(queue); // [a, b, c, d, e]
} // element方法返回队列的头元素,但不移除,若队列为空,会抛出异常:NoSuchElementException,不推荐使用
@Test
public void test4() {
// 查看首个元素
String element = queue.element();
System.out.println(element); // a
System.out.println(queue); // [a, b, c, d, e]
} }
最新文章
- 又一枚精彩的弹幕效果jQuery实现
- PostgreSQL 磁盘使用大小监控
- Spring AOP在函数接口调用性能分析及其日志处理方面的应用
- SQL Server锁定【2015.12.17】
- Extjs 实用——不定时更新
- python 中sys.stdout.write 和 print >;>; sys.stdout的区别(转)
- mysql基本内容学习过程
- linux下jdk的卸载与安装
- MES项目中出现的一个事务嵌套的使用场景
- 《SDN核心技术剖析和实战指南》2.4 OVS交换机实现分析小结
- [转] PostgreSQL的时间/日期函数使用
- Android 软键盘小知识点
- Use API to retrieve data from internet
- jQuery extend函数详解
- endnote 使用方法
- vue实现登录后跳转到之前的页面
- Docker常见仓库MySQL
- eclipse代码提示设置过常用字符还是不起作用的解决方法
- 1.4 GPU分析
- ESP32随笔汇总
热门文章
- linux ulimit具体修改服务器配置
- JSON Web Token(JWT)机制
- Swift中String与NSDate的互相转换
- ScrollView不能包含多个子项,ScrollView can host only one direct child
- MySQL架构与业务总结图
- Spark2.2+ES6.4.2(三十二):ES API之index的create/update/delete/open/close(创建index时设置setting,并创建index后根据avro模板动态设置index的mapping)
- grid - 网格项目跨行或跨列
- ui-router 1.0 001 - resolve, component, sref-active
- ASP.NET MVC 一款可预览、裁剪头像上传组件
- 如何制作initrd.img文件