Queue的add()和offer()方法有什么区别

参考答案

Queue的add()和offer()方法的区别

  • Queue 中 add() 和 offer() 都是用来向队列添加一个元素;
  • 在容量已满的情况下,add() 方法会抛出IllegalStateException异常,offer() 方法只会返回 false。

JDK1.8 源码中的解释:

  1. /**
  2. * Inserts the specified element into this queue if it is possible to do so
  3. * immediately without violating capacity restrictions, returning
  4. * {@code true} upon success and throwing an {@code IllegalStateException}
  5. * if no space is currently available.
  6. *
  7. * @param e the element to add
  8. * @return {@code true} (as specified by {@link Collection#add})
  9. * @throws IllegalStateException if the element cannot be added at this
  10. * time due to capacity restrictions
  11. * @throws ClassCastException if the class of the specified element
  12. * prevents it from being added to this queue
  13. * @throws NullPointerException if the specified element is null and
  14. * this queue does not permit null elements
  15. * @throws IllegalArgumentException if some property of this element
  16. * prevents it from being added to this queue
  17. */
  18. boolean add(E e);
  19. /**
  20. * Inserts the specified element into this queue if it is possible to do
  21. * so immediately without violating capacity restrictions.
  22. * When using a capacity-restricted queue, this method is generally
  23. * preferable to {@link #add}, which can fail to insert an element only
  24. * by throwing an exception.
  25. *
  26. * @param e the element to add
  27. * @return {@code true} if the element was added to this queue, else
  28. * {@code false}
  29. * @throws ClassCastException if the class of the specified element
  30. * prevents it from being added to this queue
  31. * @throws NullPointerException if the specified element is null and
  32. * this queue does not permit null elements
  33. * @throws IllegalArgumentException if some property of this element
  34. * prevents it from being added to this queue
  35. */
  36. boolean offer(E e);

 

以上,是Java面试题【Queue的add()和offer()方法有什么区别】的参考答案。

输出,是最好的学习方法

欢迎在评论区留下你的问题、笔记或知识点补充~

—end—

0 条回复 A文章作者 M管理员
欢迎您,新朋友,感谢参与互动!
    暂无讨论,说说你的看法吧