【问题标题】:What is the difference between pollLast() and removeLast() method of LinkedList in JavaJava中LinkedList的pollLast()和removeLast()方法有什么区别
【发布时间】:2020-07-14 03:10:54
【问题描述】:

当我看到 pollLast()removeLast() 这两种方法的定义时,它看起来很相似,它检索并删除列表的最后一个元素。

这些方法的用例是什么?

【问题讨论】:

  • 次要兴趣点:pollLast 是在 Java 1.6 中添加的,当时 LinkedList 被改造以实现 Deque 接口。

标签: java collections linked-list singly-linked-list doubly-linked-list


【解决方案1】:

如果列表为空,removeLast 将抛出 NSEE (NoSuchElementException),而如果列表为空,pollLast 将简单地返回 null。否则两者都将返回该项目并在该项目存在时将其删除。

【讨论】:

  • 如果列表为空,removeLast 不抛出 NoSuchElementException 吗?
  • 是的,我的链接 URL 正确,但文本错误。谢谢!
【解决方案2】:

这两种方法都返回List 的最后一个元素,但如果List 为空,pollLast 将返回null,而removeLast 在这种情况下会抛出NoSuchElementException

pollLast documentation:

public E pollLast() 检索并删除此列表的最后一个元素,如果此列表为空,则返回 null。

removeLast documentation:

public E removeLast() 移除并返回此列表中的最后一个元素。 抛出: NoSuchElementException - 如果此列表为空

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    相关资源
    最近更新 更多