An indexable collection of objects with a length.
An indexable collection of objects with a length.
Subclasses of this class implement different kinds of lists. The most common kinds of lists are:
Fixed-length list. An error occurs when attempting to use operations that can change the length of the list.
Growable list. Full implementation of the API defined in this class.
The default growable list, as returned by new List()
or []
, keeps
an internal buffer, and grows that buffer when necessary. This guarantees
that a sequence of add operations will each execute in amortized constant
time. Setting the length directly may take time proportional to the new
length, and may change the internal capacity so that a following add
operation will need to immediately increase the buffer capacity.
Other list implementations may have different performance behavior.
The following code illustrates that some List implementations support only a subset of the API.
List<int> fixedLengthList = new List(5);
fixedLengthList.length = 0; // Error
fixedLengthList.add(499); // Error
fixedLengthList[0] = 87;
List<int> growableList = [1, 2];
growableList.length = 0;
growableList.add(499);
growableList[0] = 87;
Lists are Iterable. Iteration occurs over values in index order. Changing the values does not affect iteration, but changing the valid indices—that is, changing the list's length—between iteration steps causes a ConcurrentModificationError. This means that only growable lists can throw ConcurrentModificationError. If the length changes temporarily and is restored before continuing the iteration, the iterator does not detect it.
It is generally not allowed to modify the list's length (adding or removing elements) while an operation on the list is being performed, for example during a call to forEach or sort. Changing the list's length while it is being iterated, either by iterating it directly or through iterating an Iterable that is backed by the list, will break the iteration.