Help me to understand. How is this
for(Car car : carPool)
change to
for(int i=1; i<10; i++)
for(int i=0; i<carPool.size(); i++) { Car car = carPool.get(i); }
Strictly speaking, it is not possible to replace foreach
with access by index (sequence number) for all collections, for example, Set
does not support such access in principle. On the other hand, it must be remembered that some collections, for example, LinkedList
with index access, spend O(n)
time to access the n
element of the collection! Iterate collection by index like carPool.get(i);
follows only if the collection supports access by index in constant time ( O(1)
). For example, classes that implement the RandomAccess
interface provide this access.
Therefore, for tasks where there is a need to know the index of the current element and not supporting access by index or requiring linear access to an element by index, you should use an iterator and count the index number in a separate variable, for example like this:
int i = 0; for (Iterator<String> iter = collection.iterator(); iter.hasNext(); i++) { String element = iter.next(); … }
IList<T>
interface that you can check to see if the collection implements efficient index access. Is there such a thing in Java? - VladDIList<T>
, all of a sudden, List<T>
. RandomAccess is just a token that index access is preferred. - Pavel MayorovLinkedList<T>
implements List<T>
, which seems a bit odd. It seemed to me that there is no effective access. - VladDSource: https://ru.stackoverflow.com/questions/543061/
All Articles