zoukankan      html  css  js  c++  java
  • Queue的add()和offer()方法有什么区别?

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

    JDK1.8 源码中的解释

    /**
     * Inserts the specified element into this queue if it is possible to do so
     * immediately without violating capacity restrictions, returning
     * {@code true} upon success and throwing an {@code IllegalStateException}
     * if no space is currently available.
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Collection#add})
     * @throws IllegalStateException if the element cannot be added at this
     *         time due to capacity restrictions
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this queue
     * @throws NullPointerException if the specified element is null and
     *         this queue does not permit null elements
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this queue
     */
    boolean add(E e);
     
    /**
     * Inserts the specified element into this queue if it is possible to do
     * so immediately without violating capacity restrictions.
     * When using a capacity-restricted queue, this method is generally
     * preferable to {@link #add}, which can fail to insert an element only
     * by throwing an exception.
     *
     * @param e the element to add
     * @return {@code true} if the element was added to this queue, else
     *         {@code false}
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this queue
     * @throws NullPointerException if the specified element is null and
     *         this queue does not permit null elements
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this queue
     */
    boolean offer(E e);

      

    来一道刷了进BAT的面试题?

  • 相关阅读:
    洛谷 P2888 [USACO07NOV]牛栏Cow Hurdles
    洛谷 P2935 [USACO09JAN]最好的地方Best Spot
    CODEVS 1172 Hankson 的趣味题
    洛谷 P2261 [CQOI2007]余数求和
    洛谷 P1463 [POI2002][HAOI2007]反素数
    洛谷 P3383 【模板】线性筛素数
    1.4.2 solr字段类型--(1.4.2.1)字段类型定义和字段类型属性
    HttpSolrServer-采用静态工厂方法,创建HttpSolrServer单实例
    将字符转换为unicode码
    solrj-WiKi
  • 原文地址:https://www.cnblogs.com/ConstXiong/p/11896127.html
Copyright © 2011-2022 走看看