Help me to understand. How is this

for(Car car : carPool) 

change to

 for(int i=1; i<10; i++) 

    2 answers 2

     for(int i=0; i<carPool.size(); i++) { Car car = carPool.get(i); } 
    • Need to change the title to understandable - Mr. Black
    • @Doofy, changed) - Yuriy SPb
    • Yeah, now caef) - Mr. Black
    • I thought I needed to change, but I'm new here too and can't use the site yet - Shirak Arshakyan
    • @AK, well, I corrected ... Although, if I did it first, then the vehicle could copy and not get what he wanted. The question was about i <10 ... I didn’t please everyone and as a result I received the most accountable answer for the years I was here ((( - YuriySPb

    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(); … } 
    • It is logical, yes. In .NET, by the way, there is an IList<T> interface that you can check to see if the collection implements efficient index access. Is there such a thing in Java? - VladD
    • @VladD, yes there is a final RandomAccess - docs.oracle.com/javase/8/docs/api/java/util/RandomAccess.html . - Mikhailov Valentine
    • Yeah, cool, thanks. - VladD
    • @VladD is still a direct analogue of IList<T> , all of a sudden, List<T> . RandomAccess is just a token that index access is preferred. - Pavel Mayorov
    • @PavelMayorov: However, LinkedList<T> implements List<T> , which seems a bit odd. It seemed to me that there is no effective access. - VladD