前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java Queue接口

Java Queue接口

作者头像
用户7886150
修改2021-04-25 17:45:58
4620
修改2021-04-25 17:45:58
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: Java队列接口

Queue接口继承自Collection接口,java.util.Queue,队列也可以保存一组元素但是存取元素必须遵循先进先出模式。 

1、常用实现类:LinkedList 

offer方法:入队操作,向队列末尾追加元素(返回值boolean类型:添加是否成功)poll方法 :出队操作,获取队首元素后该元素即从队列中被删除(返回值:元素类型,返回被出队的元素)peek方法: 引用队首元素,元素不做出队操作(返回值:元素类型:返回队首元素) 

import java.util.LinkedList;

import java.util.Queue;

public class QueueDemo {

    public static void main(String[] args) {

        Queue<String> queue = new LinkedList<>();

        //队尾添加元素

        queue.offer("one");

        queue.offer("two");

        queue.offer("three");

        System.out.println(queue);    //[one, two, three]

        //出队队首元素

        String str = queue.poll();    

        System.out.println(str);    //one

        System.out.println(queue);    //[two, three]

        //返回队首元素

        String res = queue.peek();

        System.out.println(res);    //two

        System.out.println(queue);    //[two, three]

    }

}

2、遍历队列: 

1)使用poll方法遍历队列: 

while(queue.size()>0){

    String s = queue.poll();

    System.out.println(s);

}

System.out.println(queue);

这种方法可以实现队列的遍历,但是元素遍历之后,queue会清空。 

2)使用迭代器遍历队列:元素不会因此被队列删除 

for(String s : queue){

    Sustem.out.println(s);

}

System.out.println(queue);

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档