A new Java.util.Queue interface is added to the JAVA5 to support common operations of queues. The interface extends the Java.util.Collection interface.
When the queue is used, try to avoid the collection add () and remove () methods, but instead use an offer () to add elements, use poll () to get and move the elements. Their excellent
The point is to determine success by returning a value, and the Add () and remove () methods throw an exception when they fail. If you want to use the front end without moving the element, use the
Element () or peek () method.
It is noteworthy that the LinkedList class implements the queue interface, so we can use LinkedList as a queue.
Small Example:
/**
*
* @author Zang XT
*/
Import Java.util.Queue;
Import java.util.LinkedList;
public class Testqueue {
public static void Main (string[] args) {
queue<string> queue = new linkedlist<string> ();
Queue.offer ("Hello");
Queue.offer ("world!");
Queue.offer ("Hello.") ");
System.out.println (Queue.size ());
String str;
while ((Str=queue.poll ())!=null) {
System.out.print (str);
}
System.out.println ();
System.out.println (Queue.size ());
}
}
offer,add difference:
Some queues have size limits, so if you want to add a new item to a full queue, the extra items are rejected.
The new offer method will now work. It does not throw a unchecked exception to the call to the Add () method, but only the false returned by an offer (). The
poll,remove difference:
Remove () and poll () methods remove the first element (head) from the queue. The behavior of remove () is similar to the version of the Collection interface,
But the new poll () method does not throw an exception when invoked with an empty collection, but returns NULL. Therefore, the new method is more suitable for situations that are prone to abnormal conditions. The
peek,element difference:
Element () and peek () are used to query elements in the header of the queue. Similar to the Remove () method, Element () throws an exception when the queue is empty, and peek () returns NULL.