java Queue容器实现

1、java中的Queue有点特殊,它的实现是由LinkedList完成的。

下面通过分析一个《Thinking in Java》中的代码来了解Queue的实现。

import java.util.*;

public class QueueDemo {
  public static void printQ(Queue queue) {
    while(queue.peek() != null)//peek()方法返回队首元素,但不删除该元素。属于返回逻辑值的方法类型。
      System.out.print(queue.remove() + " ");//remove()方法从队首移除一个元素。属于抛出异常的方法类型。
    System.out.println();
  }
  public static void main(String[] args) {
    Queue<Integer> queue = new LinkedList<Integer>();//创建一个Queue<Integer>,注意用LinkedList实现。
    Random rand = new Random(47);
    for(int i = 0; i < 10; i++)
      queue.offer(rand.nextInt(i + 10));//offer(e)方法向队列中加入元素。属于返回逻辑值的方法类型。
    printQ(queue);
    Queue<Character> qc = new LinkedList<Character>();
    for(char c : "Brontosaurus".toCharArray())//foreach方法
      qc.offer(c);
    printQ(qc);
  }
} /* Output:
8 1 1 1 5 14 3 1 0 1
B r o n t o s a u r u s
*/
接下来解释一下注释中的几点

①对于实现队列的同一种操作,Queue中都定义了两种返回方式的方法(a抛出异常b返回特定值)

向队列中加入元素:a、add()   b、   offer()

返回队首元素,但不删除该元素:a、elelment(), b、peek()

从队首移除一个元素:a、remove(),  b、poll()

 

②Queue使用LinkedList实现是因为Linkedlist实现了Queue接口。这还是一种上转型,LinkedList上转型为Queue类型。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值