方法
功能
异常处理
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