Java collection: iterators (Iterator, iterable)

Source: Internet
Author: User
Tags iterable concurrentmodificationexception

Iterator interface
 Public Interface Iterator<e> {    boolean  hasnext ();     E Next ();     void remove ();

Before accessing the element, it is necessary to use Hasnext to determine if there is an element, and if it is obtained by next operation, the next operation is used without hasnext detection, and the nosuchelement exception is thrown when the end is reached.

The remove operation of the iterator

For a long time without looking at the JDK code, look at the Java core today to see the point of attention in the iterator, incredibly little memory. Let's look at the following code:

        iterator<string> iter = list.iterator ();         = Iter.next ();        Iter.remove ();

So here Iter.remove () removes the element that is the first element in the list, and it is generally the same element that the iterator returned at the last time. The following code is also available:

        iterator<string> iter = list.iterator ();         = Iter.next ();        Iter.remove ();        Iter.remove ();

If the actual operation will be reported: Java.lang.IllegalStateException exception, each remove should have a corresponding next, in fact, is 22 pairs, remove is the next return of the element.

A basic implementation of iterator can be seen from the source code of Abstractlist:

1 Private classItrImplementsIterator<e> {2         /**3 * Index of element to is returned by subsequent call to next.4          */5         intcursor = 0;6 7         /**8 * Index of element returned by more recent call to next or9 * Previous. Reset To-1 If this element was deleted by a callTen * to remove. One          */ A         intLastret =-1; -  -         /** the * The Modcount value, the iterator believes that the backing - * List should has. If this expectation is violated, the iterator - * has detected concurrent modification. -          */ +         intExpectedmodcount =Modcount; -  +          Public BooleanHasnext () { A             returnCursor! =size (); at         } -  -          PublicE Next () { - checkforcomodification (); -             Try { -                 inti =cursor; inE next =get (i); -Lastret =i; tocursor = i + 1; +                 returnNext; -}Catch(indexoutofboundsexception e) { the checkforcomodification (); *                 Throw Newnosuchelementexception (); $             }Panax Notoginseng         } -  the          Public voidRemove () { +             if(Lastret < 0) A                 Throw Newillegalstateexception (); the checkforcomodification (); +  -             Try { $Abstractlist. This. Remove (Lastret); $                 if(Lastret <cursor) -cursor--; -Lastret =-1; theExpectedmodcount =Modcount; -}Catch(indexoutofboundsexception e) {Wuyi                 Throw Newconcurrentmodificationexception (); the             } -         } Wu  -         Final voidcheckforcomodification () { About             if(Modcount! =expectedmodcount) $                 Throw Newconcurrentmodificationexception (); -         } -}

You can see the Lastret and cursor two variables, which are used to represent the index of the element returned by the next () operation, which is used to represent the index value of the element that should be returned the next next () call. Each time the remove Operation Lastret is emptied, and cursor--, because the lastret corresponds to the element in front of the cursor, and when it is removed, then the cursor value must be reduced by one. In fact, the implementation of the iterator here is basically covered by abstractlist subclasses, such as Linkedlist,arraylist. The former does not support random access must not use the index value as the implementation of the acquisition element, otherwise the efficiency of the iterator is too low.

Listiterator (extends Iterator<e>)

In addition to inheriting the Iterable interface, the list interface has several additional methods (Listiterator) to obtain an iterator specifically for the list (that is, listiterator) to see the LinkedList iterator implementation:

Private classListitrImplementsListiterator<e> {        PrivateNode<e> lastreturned =NULL; PrivateNode<e>Next; Private intNextindex; Private intExpectedmodcount =Modcount; Listitr (intindex) {            //assert Ispositionindex (index);Next = (index = = size)?NULL: node (index); Nextindex=index; }         Public BooleanHasnext () {returnNextindex <size; }         PublicE Next () {checkforcomodification (); if(!Hasnext ())Throw Newnosuchelementexception (); lastreturned=Next; Next=Next.next; Nextindex++; returnLastreturned.item; }         Public Booleanhasprevious () {returnNextindex > 0; }         PublicE Previous () {checkforcomodification (); if(!hasprevious ())Throw Newnosuchelementexception (); lastreturned= Next = (Next = =NULL) ?Last:next.prev; Nextindex--; returnLastreturned.item; }         Public intNextindex () {returnNextindex; }         Public intPreviousindex () {returnNextIndex-1; }         Public voidRemove () {checkforcomodification (); if(lastreturned = =NULL)                Throw Newillegalstateexception (); Node<E> Lastnext =Lastreturned.next;            Unlink (lastreturned); if(Next = =lastreturned) Next=Lastnext; ElseNextindex--; lastreturned=NULL; Expectedmodcount++; }         Public voidset (e e) {if(lastreturned = =NULL)                Throw Newillegalstateexception ();            Checkforcomodification (); Lastreturned.item=e; }         Public voidAdd (e e) {checkforcomodification (); lastreturned=NULL; if(Next = =NULL) Linklast (e); ElseLinkbefore (E, next); Nextindex++; Expectedmodcount++; }        Final voidcheckforcomodification () {if(Modcount! =expectedmodcount)Throw Newconcurrentmodificationexception (); }    }

The idea for the remove operation is broadly consistent except that Lastret is replaced with a list node lastreturned, which is also set to null after each remove. The get element is not obtained directly through get (i), as in the parent version. The iterator saves two adjacent node pointers lastreturned and next. When the element is removed (lastreturned=null), it can still be moved in the linked list because the next pointer value is saved when you call next again.

Compared to the iterator interface, the Listiterator interface has an Add method that puts the element in the position before the next element that the iterator points to, the position before the next element.

Iterable interface
 Public Interface Iterable<t> {    /**     * Returns An iterator over a set of elements of type T.     *     @return an Iterator.      */     Iterator<T> Iterator ();}

As described in Java core, if we implement the Iterable interface then it can be used in a foreach loop. Such as

classMyCollectionImplementsIterable<integer>{@Override PublicIterator<integer>iterator () {return NewIterator<integer>() {             Public intCount = 0; @Override Public BooleanHasnext () {returnCount < 10; } @Override PublicInteger Next () {returncount++; } @Override Public voidRemove () {Throw Newunsupportedoperationexception ();    }        }; }} Public classFieldsImplementsConst { Public Static voidMainFinalstring[] args) {mycollection mycollection=Newmycollection ();  for(Integer i:mycollection) {System.out.println (i); }    }}

Java collection: iterators (Iterator, iterable)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.