所以,为了获得最有效的代码,我真的很想知道size()
Java 中的方法是如何ArrayList
工作的......它是否计算每个元素,遍历所有位置,就像一个简单的列表?还是它只是通过注册的最后一个索引获取大小?
提前致谢!
所以,为了获得最有效的代码,我真的很想知道size()
Java 中的方法是如何ArrayList
工作的......它是否计算每个元素,遍历所有位置,就像一个简单的列表?还是它只是通过注册的最后一个索引获取大小?
提前致谢!
在最新的 Java7 中,它所做的不仅仅是读取成员字段值:
public int size() {
checkForComodification();
return this.size;
}
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
其中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;
}
根据 的源代码ArrayList
,该size()
方法返回一个名为 的私有变量size
,它只是一个每次递增的计数器add
。
它读取一个字段变量。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;
}