Java Iterable interface and Iterator

Source: Internet
Author: User
Tags concurrentmodificationexception java iterable

Java Iterable interface and Iterator
Java Iterable interface and Iterator iterator Iterator

The interface is defined as follows:

public interface Iterator
  
    {    boolean hasNext();    E next();    void remove();}
  

This interface only contains three functions. The hasNext () and next () methods appear in our common set traversal.
Functions:

Use next () to obtain the next element in the sequence. Use hasNext () to check whether there are any elements in the sequence. Use remove () to delete the elements returned by the iterator.

For a set that has implemented the iterator interface, the traversal set is generally written
For example, the list set, which we commonly use, has implemented the iterator interface.
-Method 1:

 list l = new ArrayList(); l.add(aa); l.add(bb); l.add(cc);  for (Iterator iter = l.iterator(); iter.hasNext();) {  String str = (String)iter.next();  System.out.println(str); }
Method 2: while
 Iterator iter = l.iterator(); while(iter.hasNext()){  String str = (String) iter.next();  System.out.println(str); }

Here, let's look at the javasactlist source code. The iterator implementation details are in the middle. The iter above is actually a polymorphism, And the iterator method in the list abstract javasactlist class is called:

 private class Itr implements Iterator
  
    {        int cursor = 0;        int lastRet = -1;        int expectedModCount = modCount;        public boolean hasNext() {            return cursor != size();        }        public E next() {            checkForComodification();            try {                int i = cursor;                E next = get(i);                lastRet = i;                cursor = i + 1;                return next;            } catch (IndexOutOfBoundsException e) {                checkForComodification();                throw new NoSuchElementException();            }        }        public void remove() {            if (lastRet < 0)                throw new IllegalStateException();            checkForComodification();            try {                AbstractList.this.remove(lastRet);                if (lastRet < cursor)                    cursor--;                lastRet = -1;                expectedModCount = modCount;            } catch (IndexOutOfBoundsException e) {                throw new ConcurrentModificationException();            }        }        final void checkForComodification() {            if (modCount != expectedModCount)                throw new ConcurrentModificationException();        }    }
  

Through the source code, we can see more clearly the implementation mechanism of the three functions of iterator. careful readers may find that expectedModCount = modCount; In the move () method has such an expression. This is actually a fast Failure Mechanism in the list. The addition and deletion of modcount in the arraylist changes the value, and expectedModcount is the value maintained in the traversal. If the two are not equal, a write operation occurs during the traversal. This causes data inconsistency.
For details, refer to the blog [ConcurrentModificationException] [1].

The benefits of using iterator can be summarized as follows:
**

Encapsulate the internal implementation details of the container. For different sets, the same Traversal method can be provided to simplify client access and obtain data in the container.

**

Iterable

The interface is defined as follows:

public interface Iterable
  
    {    /**     * Returns an iterator over a set of elements of type T.     *     * @return an Iterator.     */    Iterator
   
     iterator();}
   
  

Java SE5 introduces the Iterable interface, which contains an Iterator () method that can generate iterator, And the Iterable interface is used by foreach to move in the sequence. Therefore, any custom class that implements Iterable can be used in the foreach statement.

Iterable is mainly used to implement the Iterable interface to implement custom classes suitable for foreach traversal.

Let's look at a simple example:

package com.andieguo.iterabledemo;import java.util.Iterator;public class IterablerClass
  
    implements Iterable
   
    {    private T[] array = null;    public IterablerClass(T[] t){        this.array = t ;    }    @Override    public Iterator
    
      iterator() {        // TODO Auto-generated method stub        return new Iterator
     
      () {            private Integer index = 0;            @Override            public boolean hasNext() {                // TODO Auto-generated method stub                return index iterablerClass = new IterablerClass
      
       (new String[]{hello,world,today,happy,sorrow}); for(String s:iterablerClass){ System.out.print(s+ ); } }}
      
     
    
   
  

 

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.