【问题标题】:How does size( ) works in java's ArrayList class?size() 在 java 的 ArrayList 类中是如何工作的?
【发布时间】:2013-03-08 21:29:59
【问题描述】:

所以,为了获得最有效的代码,我真的很想知道 Java 中的 size() 方法 ArrayList 是如何工作的...它是否计算每个元素,遍历所有位置,就像一个简单的列表?还是只是通过最后注册的索引获取大小?

提前致谢!

【问题讨论】:

标签: java arraylist performance


【解决方案1】:

查看source code 不会有什么坏处:

public int size() {
    return size;
}

它返回一个实例变量——非常快。

【讨论】:

  • 您引用的是 OpenJDK 源代码,而不是 Sun 官方源代码
  • @SteveKuo - OpenJDK 有效的 Sun 源(已关闭,无法发布到公共论坛)。
【解决方案2】:

在最新的 Java7 中,它所做的不仅仅是读取成员字段值:

public int size() {
    checkForComodification();
    return this.size;
}

private void checkForComodification() {
    if (ArrayList.this.modCount != this.modCount)
        throw new ConcurrentModificationException();
}

【讨论】:

    【解决方案3】:

    ArrayList 中有一个int 属性用于存储当前大小(例如,称为size)。显然,为了提高效率,计算数组列表的大小应该是一个O(1) 操作。即使在诸如LinkedList(双链表)之类的数据结构中,大小也会在属性中保持更新,以避免每次需要时都必须计算它。要更清楚地看到它,请查看 OpenJDK 中的 source code,您会发现:

     /**
      * The size of the ArrayList (the number of elements it contains).
      *
      * @serial
      */
      private int size;
    
     /**
      * Returns the number of elements in this list.
      *
      * @return the number of elements in this list
      */
      public int size() {
          return size;
      }
    

    【讨论】:

      【解决方案4】:

      根据ArrayList 的源代码,size() 方法返回一个名为size 的私​​有变量,它只是一个在每个add 上递增的计数器。

      【讨论】:

        【解决方案5】:

        它读取一个字段变量。 Java 1.6 的ArrayList.size():

        /**
         * Returns the number of elements in this list.
         *
         * @return the number of elements in this list
         */
        public int size() {
            return size;
        }
        

        【讨论】:

          猜你喜欢
          • 2011-01-13
          • 2011-03-28
          • 2015-08-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-02
          • 2017-05-03
          • 1970-01-01
          相关资源
          最近更新 更多