offer、add
add()和offer()都是向队列中添加一个元素,一些队列有大小限制,因此如果想在一个满的队列中加入一个新项,调用 add() 方法就会抛出一个 unchecked 异常,而调用 offer() 方法会返回 false。因此就可以在程序中进行有效的判断!
offer()在队列满时返回false
add()在队列满时抛出异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class JavaQueue { public static void main(String[] args) { Queue<Integer> queue = new LinkedBlockingQueue<>(3); queue.add(1); queue.add(2); queue.add(3);
boolean isSucceed = queue.offer(3); System.out.println(isSucceed); } }
|
poll、remove
remove()和poll()方法都是从队列中删除第一个元素,如果队列为空,调用remove() 的行为与 Collection 接口的版本相似会抛出异常。但是 poll() 方法在用空集合调用时只是返回 null。因此新的方法更适合容易出现异常条件的情况。
poll()在空队列返回null
add()在空队列抛出异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public class JavaQueue { public static void main(String[] args) { Queue<Integer> queue2 = new LinkedBlockingQueue<>(3);
Integer integer = qeue2.poll(); System.out.println(integer); } }
|
element、peek
element() 和 peek() 用于在队列的头部查询元素。与 remove() 方法类似,在队列为空时, element() 抛出一个异常,而 peek() 返回 null。
peek()在空队列返回null
element()在空队列抛出异常
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
public class JavaQueue { public static void main(String[] args) { Queue<Integer> queue3 = new LinkedBlockingQueue<>(3);
Integer integer2 = queue3.peek(); System.out.println(integer2);
} }
|