Java iterators -- Iterator and Iterable interfaces

Source: Internet
Author: User
Keywords Java iterators iterable interface
Tags java java iterators iterable interface iterator interface

Iterator interface

Iterator is mainly used to manipulate collection objects in java. Iterators provide a uniform syntax for collection traversal operations without the need to care about the internal implementation of collection objects. Java provides an iterator interface Iterator. Iterator can only move forward and cannot be rolled back.

The declaration of java's iterator interface is as follows:

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

As you can see from the interface code above, the Iterator interface has only three no-argument methods.

Method  
Return
Value Exception
 Description
hasNext
bool
no Determine if there is another object, if it is, return true, otherwise false
next
E NoSuchElementException
Returns the next value of the collection, this method can only be called when the hasNext method returns true
remove
void IllegalStateException
Delete the current value of the collection. This method can only be called when the hasNext method returns true.

Iterable interface
After jdk1.5, the Iterable interface was added to support the foreach loop. The Iterable interface has only one method, the iterator() method, which returns the collection's Iterator object. All collections that implement the Iterable interface can be traversed using a foreach loop.
The source code for Iterable is as follows:
public interface Iterable<T> {
    Iterator<T> iterator();
}
The difference between Iterator and Iterable
As you can see from the above, the Iterator interface provides a unified way to traverse collection elements. You can use the Iterator object to care about the concrete type and internal implementation of a specific collection object. You can use the Iterator object's interface method to traverse the collection.
The Iterable interface is designed for the foreach loop. The Iterable interface means that a collection can return an Iterator object. Finally, iterate through the Iterator.
Set traversal and deletion
In the collection framework of java, a Set is a collection that cannot contain duplicate elements. The Set object can be traversed using the Iterator object, and the Set collection also inherits the Iterable interface, so it supports foreach loops. Examples of use are as follows:
public class IteratorTest {
    static void testSet(){
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(3);
        Iterator<Integer> setIter = set.iterator();
        while (setIter.hasNext()){
            if (setIter.next() == 2){
                setIter.remove();
            }
        }

        for (int i:set){
            System.out.println(i);
        }
    }

    public static void main( String[] args ) {
        testSet();
    }
}

In the above example, the Iterator object is used to iterate over the Set collection, while the 2 elements are removed, using a foreach loop, and finally the output.
1
3
List traversal and delete
In the collection framework of java, the difference between List and Set is that List can contain repeating elements and can be traversed using subscripts. The List object can also be traversed using the Iterator object, and the List collection also inherits the Iterable interface, so it supports foreach loops. Examples of use are as follows:
public class IteratorTest {
    static void testList(){
        List<Integer> testList = new ArrayList<>();
        testList.add(1);
        testList.add(2);
        testList.add(3);

        Iterator<Integer> iter = testList.iterator();
        while (iter.hasNext()){
            if (iter.next() == 2){
                iter.remove();
            }
        }

        for (int i:testList){
            System.out.println(i);
        }
    }

    public static void main( String[] args ) {
        testList();
    }
}
In the above example, the Iterator object is used to traverse the List collection, while deleting the 2 element, using the foreach loop, and finally outputting
1
3
Although List collections can also use subscripts for traversal loops, it is most convenient to use Iterator if you want to remove objects that satisfy certain conditions in the traversal.
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.