What is the fastest way to get the first n elements of a list stored in an array?
Considering this as the scenario:
int n = 10;
ArrayList
Option 3
Iterators are faster than using the get
operation, since the get
operation has to start from the beginning if it has to do some traversal. It probably wouldn't make a difference in an ArrayList, but other data structures could see a noticeable speed difference. This is also compatible with things that aren't lists, like sets.
String[] out = new String[n];
Iterator iterator = in.iterator();
for (int i = 0; i < n && iterator.hasNext(); i++)
out[i] = iterator.next();