Java 中佇列的使用示例及常用方法示例和比較
阿新 • • 發佈:2018-12-29
在java5中新增加了java.util.Queue介面,用以支援佇列的常見操作。
Queue介面與List、Set同一級別,都是繼承了Collection介面。
Queue使用時要儘量避免Collection的add()和remove()方法,而是要使用offer()來加入元素,使用poll()來獲取並移出元素。
新加的方法肯定有好處,不然幹嘛加他,直接用add和remove方法不就好啦。add()和remove()方法在失敗的時候會丟擲異常。
如果要使用前端而不移出該元素,使用 element()或者peek()方法。
值得注意的是LinkedList類實現了Queue介面,因此我們可以把LinkedList當成Queue來用。
LinkedList實現了Queue介面。
附上使用的示例程式碼,如下:
然後就是證明上面的結論是正確的,看看了佇列這個介面的程式碼,如下:真不多。一共就六個方法。import java.util.LinkedList; import java.util.Queue; class Hello { public static void main(String[] a) { Queue<String> queue = new LinkedList<>(); queue.offer("1");//插入一個元素 queue.offer("2"); queue.offer("3"); //列印元素個數 System.out.println("queue.size() " + queue.size());//queue.size() 3 //遍歷列印所有的元素,按照插入的順序列印 for (String string : queue) { System.out.println(string); } System.out.println("queue.size() " + queue.size());//queue.size() 3 上面只是簡單迴圈,沒改變佇列 String getOneFrom1 = queue.element(); System.out.println("getOneFrom1 " + getOneFrom1);//getOneFrom1 1 因為使用前端而不移出該元素 System.out.println("queue.size() " + queue.size());//queue.size() 3 佇列變啦才怪 String getOneFrom2 = queue.peek(); System.out.println("getOneFrom2 " + getOneFrom2);//getOneFrom2 1 因為使用前端而不移出該元素 System.out.println("queue.size() " + queue.size());//queue.size() 3 佇列變啦才怪 String getOneFrom3 = queue.poll(); System.out.println("getOneFrom3 " + getOneFrom3);//getOneFrom3 1 獲取並移出元素 System.out.println("queue.size() " + queue.size());//queue.size() 2 佇列變啦 } }
//摘自Java 1.8 原始碼,註釋摘一半不到.這個介面,就這麼幾個方法,好幸福啊,這麼少。 public interface Queue<E> extends Collection<E> { /** * Inserts the specified element into this queue if it is possible to do so * immediately without violating capacity restrictions, returning * {@code true} upon success and throwing an {@code IllegalStateException} * if no space is currently available. * ...... */ boolean add(E e);//比offer多丟了個異常,跟容量相關 /** * Inserts the specified element into this queue if it is possible to do * so immediately without violating capacity restrictions. * When using a capacity-restricted queue, this method is generally * preferable to {@link #add}, which can fail to insert an element only * by throwing an exception. * ...... */ boolean offer(E e); /** * Retrieves and removes the head of this queue. This method differs * from {@link #poll poll} only in that it throws an exception if this * queue is empty. * ...... */ E remove();//與poll的差別是當佇列是空的時候,這個要報異常,下面返回null /** * Retrieves and removes the head of this queue, * or returns {@code null} if this queue is empty. * .... */ E poll(); /** * Retrieves, but does not remove, the head of this queue. This method * differs from {@link #peek peek} only in that it throws an exception * if this queue is empty. * ...... */ E element();//當佇列空的時候異常,下面的只是返回null /** * Retrieves, but does not remove, the head of this queue, * or returns {@code null} if this queue is empty. * ...... */ E peek(); }