Queue队列

/**
 * 在java5中新增加了java.util.Queue接口,用以支持队列的常见操作。该接口扩展了java.util.Collection接口。
 * Queue使用时要尽量避免Collection的add
 * ()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优
 * 点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 如果要使用前端而不移出该元素,使用
 * element()或者peek()方法。 值得注意的是LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。
 *
 * @author Dminter
 *
 */
public class TestQueue {
 public static void main(String[] args) {
  Queue queue = new LinkedList();
  queue.offer("1");
  queue.offer("2");
  queue.offer("3");
  System.out.println(queue.size());// 3
  String str;
  while ((str = queue.poll()) != null) {
   System.out.print(str);// 123
  }
  System.out.println();
  System.out.println(queue.size());// 0
 }
}

你可能感兴趣的:(JAVA)