Queue的poll() 和offer()

博客探讨了在Java中队列操作中,add()与offer()的区别,指出add()在队列满时会抛出异常,而offer()则直接返回false。同时,解释了Queue中remove()与poll()的使用场景,当队列为空时,remove()会抛出异常,poll()则返回null。这些细节对于理解和避免程序错误至关重要。
摘要由CSDN通过智能技术生成

add():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never throw IllegalStateException or return false.
在这里插入图片描述

offer():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never return false.

在这里插入图片描述

区别:两者都是往队列尾部插入元素,不同的是,当超出队列界限的时候,add()是抛出异常让你处理,而offer()是直接返回false。
leetcode一般用offer()。

同理

  • Queue 中 remove() 和 poll()有什么区别?

Queue 中 remove() 和 poll()都是用来从队列头部删除一个元素。
在队列元素为空的情况下,remove() 方法会抛出NoSuchElementException异常,poll() 方法只会返回 null 。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值