java queue 队列_java队列——queue浅析

方法

功能

异常处理

add

增加一个元索

如果队列已满,则抛出一个IIIegaISlabEepeplian异常

remove

移除并返回队列头部的元素

如果队列为空,则抛出一个NoSuchElementException异常

element

返回队列头部的元素

如果队列为空,则抛出一个NoSuchElementException异常

offer

添加一个元素并返回true

如果队列已满,则返回false

poll

移除并返问队列头部的元素

如果队列为空,则返回null

peek

返回队列头部的元素

如果队列为空,则返回null

put

添加一个元素

如果队列满,则阻塞

take

移除并返回队列头部的元素

如果队列为空,则阻塞

下面是我测试的remove()方法和poll()方法

remove(),如果队列为空,则抛出一个NoSuchElementException异常

import java.util.LinkedList;

public class LinkedListTest {

public static void main(String[] args) {

LinkedList linkedList = new LinkedList<>();

boolean offerFlag1 = linkedList.offer("ai");

boolean offerFlag2 = linkedList.offer("love");

String pollValue = linkedList.poll();

linkedList.remove();

linkedList.remove();

linkedList.remove();

for (String s : linkedList) {

System.out.println(s);

}

System.out.println("移出的元素:"+pollValue);

}

}

输出

Exception in thread "main" java.util.NoSuchElementException

at java.util.LinkedList.removeFirst(LinkedList.java:270)

at java.util.LinkedList.remove(LinkedList.java:685)

at com.LinkedListTest.main(LinkedListTest.java:12)

poll()如果队列为空,则返回null

import java.util.LinkedList;

public class LinkedListTest2 {

public static void main(String[] args) {

LinkedList linkedList = new LinkedList<>();

boolean offerFlag1 = linkedList.offer("ai");

boolean offerFlag2 = linkedList.offer("love");

// 移出元素

String pollValue = linkedList.poll();

String poll = linkedList.poll();

String poll2 = linkedList.poll();

for (String string : linkedList) {

System.out.println(string);

}

System.out.println("移出的元素:" + pollValue);

System.out.println("移出的元素:" + poll);

System.out.println("移出的元素:" + poll2);

}

}

输出

移出的元素:ai

移出的元素:love

移出的元素:null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值