[Java] java Queue (LinkedList)代码示例 →→→→→进入此内容的聊天室

来自 , 2021-01-12, 写在 Java, 查看 162 次.
URL http://www.code666.cn/view/c1722a79
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3.  
  4. /**
  5.  *
  6.  * @author outofmemory.cn
  7.  */
  8. public class Main {
  9.  
  10.     /**
  11.      * Example method for using a Queue
  12.      */
  13.     public void queueExample() {
  14.  
  15.         Queue queue = new LinkedList();
  16.  
  17.         //Using the add method to add items.
  18.         //Should anything go wrong an exception will be thrown.
  19.         queue.add("item1");
  20.         queue.add("item2");
  21.  
  22.         //Using the offer method to add items.
  23.         //Should anything go wrong it will just return false
  24.         queue.offer("Item3");
  25.         queue.offer("Item4");
  26.  
  27.         //Removing the first item from the queue.
  28.         //If the queue is empty a java.util.NoSuchElementException will be thrown.
  29.         System.out.println("remove: " + queue.remove());
  30.  
  31.         //Checking what item is first in line without removing it
  32.         //If the queue is empty a java.util.NoSuchElementException will be thrown.
  33.         System.out.println("element: " + queue.element());
  34.  
  35.         //Removing the first item from the queue.
  36.         //If the queue is empty the method just returns false.
  37.         System.out.println("poll: " + queue.poll());
  38.  
  39.         //Checking what item is first in line without removing it
  40.         //If the queue is empty a null value will be returned.
  41.         System.out.println("peek: " + queue.peek());
  42.  
  43.     }
  44.  
  45.     /**
  46.      * @param args the command line arguments
  47.      */
  48.     public static void main(String[] args) {
  49.         new Main().queueExample();
  50.     }
  51. }
  52. //java/6683

回复 "java Queue (LinkedList)代码示例"

这儿你可以回复上面这条便签

captcha