There is an ArrayList of 10 elements. How to iterate from 4th to 8th element using iterators?

In C ++, this did not create such problems for me))

    2 answers 2

    list.subList(fromIndex, toIndex).iterator(); 

    Or through for-each:

     for(Type element : list.subList(fromIndex, toIndex) { // do something } 

    Notice that the subList returns a representation of a portion of the list from the element with the index fromIndex, by the toIndex element not including the last one.

    • Thanks, perfect. - linya

    The List interface has a get (int position) method.

    If we really really want to just iterators, then again, the List interface contains the listIterator () method and listIterator (int location) , which return an iterator from the beginning of the collection and from a certain position, respectively.

    • Comrades anonymous minus are so funny :) - falstaf
    • I know about this, please add your answer. Here the same code will not work. ListIterator <Float> i_begin = array.listIterator (4); ListIterator <Float> i_end = array.listIterator (8); for (ListIterator <Float> i = i_begin; i! = i_end;) {Float test = i.next (); } How to make the code work? - linya
    • one
      And yet, what is the alternative with get to you: for (int i = 4; i <8; ++ i) {final float value = array.get (i); } I do not like? Well, about iterators - they have methods bool hasNext () and T next () - then, I think, you will understand. - falstaf
    • Thank you, you did not help me. - linya
    • and how beautiful it is done in c ++? and where do the +2 arguments to the function come from? - Gorets