iDecode
iDecode

Reputation: 28976

What's the difference between [] and elementAt in List?

var ints = [0, 1, 2, 3];
var foo = ints.elementAt(1);
var bar = ints[1];
assert(foo == bar);

Both elementAt and [] operator do the same job. Is there any difference between the two and if no, then why there is no [] defined in Iterable class when we can use elementAt on them?

Upvotes: 7

Views: 1176

Answers (1)

jamesdlin
jamesdlin

Reputation: 90095

In most languages, [] is usually expected to be fast: it's often O(1) (or sometimes O(log n)) for accessing random elements. Allowing [] to access elements of a linked list would be technically possible, but it usually would be a bad idea since it'd make potential performance problems less obvious. Most people would not expect someCollection[99] to perform 100 iterations.

In contrast, elementAt does not make any such guarantee:

May iterate through the elements in iteration order, ignoring the first index elements and then returning the next. Some iterables may have a more efficient way to find the element.

So any Iterable always can provide an elementAt implementation, which is not necessarily fast, but only derived classes that can provide efficient implementations should provide operator []. For such classes, elementAt and [] should be the same.

Upvotes: 8

Related Questions