Queue的使用

Queue

FIFO(First-in,First-out)
Queue在并发编程中十分重要。
LinkedList有支持Queue行为的方法,它实现了Queue接口,所以LinkedList可以作为Queue实现。

方法

  • offer():在Queue尾插入元素,如果插入失败返回false;
  • peek():返回Queue头元素(不删除),如果没有返回null;
  • element():返回Queue头元素(不删除),如果没有抛出NoSuchElementException()异常;
  • poll():删除并返回头元素,如果没有返回null;
  • remove():删除并返回头元素,如果没有抛出NoSuchElementException()异常;

例:

import java.util.*;

public class QueueDemo {

    public static void printQ(Queue queue) {
        while (queue.peek() != null) {
            System.out.print(queue.remove() + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<Integer>();
        Random rand = new Random(47);
        for (int i = 0; i < 10; i++) {
            queue.offer(rand.nextInt(i + 10));
        }
        printQ(queue);
        Queue<Character> qc = new LinkedList<Character>();
        for (char c : "HelloWorld".toCharArray())
            qc.offer(c);
        printQ(qc);
    }
}

PriorityQueue(待续)

通过自己的comparator,改变元素的顺序。
当调用peek(),remove(),poll()得到的是优先级最高的元素。

Integer,String,Charator应用于PriorityQueue是因为它们有自然顺序。如果想要在PriorityQueue中加入自己的对象,就必须包含额外的产生自然顺序的函数或者提供自己的Comparator()。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值