3

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

提前致谢!

4

5 回答 5

5

查看源代码永远不会受到伤害:

public int size() {
    return size;
}

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

于 2013-03-19T23:34:17.563 回答
2

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

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

private void checkForComodification() {
    if (ArrayList.this.modCount != this.modCount)
        throw new ConcurrentModificationException();
}
于 2013-03-19T23:36:23.660 回答
1

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

 /**
  * 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;
  }
于 2013-03-19T23:35:18.077 回答
0

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

于 2013-03-19T23:34:37.157 回答
0

它读取一个字段变量。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;
}
于 2013-03-19T23:34:37.687 回答