java 队列 queue 使用_java.util.Queue(队列)的简单使用

java.util.Queue(队列)的简单使用

发布时间:2018-12-17 17:15,

浏览次数:1291

, 标签:

Queue队列,java

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 queue;

@Before

public void before() {

// 实例化队列变量

queue = new LinkedList();

// 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]

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值