全部博文(2065)
分类: Java
2010-04-29 22:48:56
Java中的Queue
[学习时间:
此类包含了五个方法分别为:
Offer
往一个队列里面插入元素。fail to insert an
element only by throwing an exception.
Poll
Retrieves and
removes the head of this queue, or null if this queue is empty.
检索并将队列的头部删除掉。如果队列为空的话就返回null
Remove
Retrieves and
removes the head of this queue. This method differs from the poll method in
that it throws an exception if this queue is empty.
检索并且将队列头删除掉。
Peek
Retrieves, but
does not remove, the head of this queue, returning null if this queue is empty.
提取但是不删除。如果队列为空的话就返回null值了。
Element()
Retrieves, but
does not remove, the head of this queue. This method differs from the peek
method only in that it throws an exception if this queue is empty.
如果队列为空的话就会抛异常!
示例代码
import
java.util.LinkedList;
import java.util.Queue;
public class Test {
public static void
main(String[] args) {
Queue
queue = new LinkedList();
queue.add("item1");
queue.add("item2");
queue.offer("item3");
queue.offer("item4");
if (!queue.isEmpty()) {
System.out.println("remove:"
+ queue.remove());
System.out.println("element:"
+ queue.element());
}
if (queue.peek() == null)
throw new NullPointerException();
System.out.println("peek:"
+ queue.peek());
System.out.println("Poll:"
+ queue.poll());
}
}