Java队列详解之 LinkedList
类
1. 类简介
- 类释义
A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the operation fails, the other returns a special value (either null or false, depending on the operation). The latter form of the insert operation is designed specifically for use with capacity-restricted Queue implementations; in most implementations, insert operations cannot fail.
用于在处理前保存元素而设计的 Collection
【说明这个是继承自 Collection
接口】
- 继承关系
2. 类方法
2.1 add
方法
Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
2.2 peek
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
2.3 poll
Retrieves and removes the head of this queue, or returns null if this queue is empty.
2.4 contains
Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (onull ? enull : o.equals(e)).
3. 简单示例
- 示例 1
public Queue<String> getFreeIpInQueue(WebSite webSite) {
Queue<String> queue = new LinkedList <String>();
queue.add("a");
queue.add("b");
System.out.println(queue.size());
for (String s : queue) {
System.out.println("The content is: "+s);
}
//peek: Retrieves, but does not remove, the head of this queue or returns null if this queue is empty.
System.out.println("peek of queue is: "+queue.peek());
System.out.println("after peek() "+queue.size());
//Retrieves and removes the head of this queue, or returns null if this queue is empty.
System.out.println(""+queue.poll());
System.out.println("after poll() "+queue.size());
return queue;
}
执行结果如下:
- 示例2
public static void main(String[] args) {
Queue<String> queue = new LinkedList<String>();
queue.add("118.187.58.34 53281");
queue.add("219.234.5.128 3128");
queue.add("113.121.243.38 808");
System.out.println(queue.size());
//contains: Returns true if this collection contains the specified element.
if(queue.contains("113.121.243.38 808")){
System.out.println("113.121.243.38 808 has been in queue! Don't add again");
}
}