Java Collection Large family of iterators

Source: Internet
Author: User
Introduction

Any container, there must be some way to insert the elements and retrieve them again. For the list container, add () is one of the methods to insert the element, and get () is one of the methods for fetching the element. To use a container, you must program the exact type of the container, if it was originally encoded in the list, but later found it would be convenient to apply the same code to the set. iterator

The concept of an iterator iterator(also a design pattern) can be used to achieve this goal. An iterator is an object that works by traversing and selecting objects in a container without having to worry about what the container's type is. In addition, iterators are often referred to as lightweight objects: the cost of creating it is small. Java iterator can only move in one direction. The container uses the iterator () method to return an element that the Iterator,iterator will be ready to return to the container.

The iterator interface defines the following methods:

Hasnext (): Detects if there are any elements in the container, if any, returns true. Next (): Gets the next element in the container. Remove (): Removes the element that is generated by next (), so the remove must be called after next (). Remove is an optional method, that is, not all iterator implementation classes must implement this method.

public static void display (Iterator<integer> it) {while (It.hasnext ()) {
        System.out.print (It.next () + "");
    } System.out.println (); public static void Main (string[] args) {list<integer> ll = arrays.aslist (78, 94, 54, 12, 5, 69,-8, 4
        8, 48, 984, 14);
        Linkedlist<integer > Link=new linkedlist<> (LL);
        hashset<integer> set = new hashset<> (ll);
        treeset<integer> tree = new treeset<> (ll);
        Print display (Ll.iterator ());
        Display (Link.iterator ());
        Display (Set.iterator ());
    Display (Tree.iterator ()); /*OUTPUT:78 94 54 12 5 69-8 48 48 984 14 78 94 54 12 5 69-8 48 48 984 14 48 5 69 54-8 984 12 78 94 14-8 5 984 */

The display () method does not contain any type information about it traversing the container, and iterator the ability to separate the operations of the traversal sequence from the underlying deconstruction, which is the way to connect the methods of the queue and the consumption queue to the least coupling degree. Because of this, the iterator unifies the way the container is accessed . Iterable Interface

The container in the example above is a container of the collection type, and it can be said that all collection type containers can use iterators , and not collection type containers cannot iterate directly using iterators. As a map, you can only use iterators for key sequences or value sequences. The reason that collection types of containers can use iterators is that the collection interface inherits the Iterable interface, which contains a iterator () method that can produce iterator:

Public interface Collection<e> extends iterable<e> {
Public interface Iterable<t> {
    /**
     * Returns ' {@link iterator} for the ' elements in ' this object.
     *
     * @return an {@code iterator} instance.
     * *
    iterator<t> iterator ();
}

To present the iterative principle of the iterator, we can implement a simple container:

public class MyCollection extends abstractcollection<integer> {private integer[] arrays = {78, 59,-7, 15, 29,
    10, 48, 2, 4}; @Override public iterator<integer> iterator () {return new iterator<integer> () {Priva
            Te int index = 0;
            @Override public boolean Hasnext () {return index < arrays.length;
            @Override public Integer Next () {return arrays[index++]; @Override public void Remove () {throw new Unsupportedoperationexception ("Remove")
            ");
    }
        };
    @Override public int size () {return arrays.length;
        public static void Main (string[] args) {mycollection mycollection=new mycollection ();
    Display (Mycollection.iterator ()); public static void display (Iterator<integer> it) {while (It.hasnext ()) {SystEm.out.print (It.next () + "");
    } System.out.println (); }
}

Output:
78 59-7 15 29 10 48 2 4

If we want to implement our own container class, we do not need to implement the collection interface directly, but inherit the Abstractcollection class, because the Abstractcollection class also implements the collection interface. But it provides a lot of default implementations for collection, allowing you to create abstractcollection subtypes without having to write too many repetitive code. We can see that if you implement the collection, you must implement the iterator () method , you must implement the iterator interface, and the method defined in iterator is next (), Hasnext () We need to implement how to iterate the elements ourselves. This is why using iterators can traverse the collection container. iterable interface and foreach

We know that the foreach syntax is primarily used for arrays, but it can also be used with any collection object. The reason is that the Iterable interface can be used by foreach to move through a sequence. If you create any iterable class, you can use it in a foreach statement :

public class MyCollection extends abstractcollection<integer> {private integer[] array
    s = {78, 59,-7, 15, 29, 10, 48, 2, 4}; @Override public iterator<integer> iterator () {return new iterator<integer> () {Priva
            Te int index = 0;
            @Override public boolean Hasnext () {return index < arrays.length;
            @Override public Integer Next () {return arrays[index++]; @Override public void Remove () {throw new Unsupportedoperationexception ("Remove")
            ");
    }
        };
    @Override public int size () {return arrays.length;
        public static void Main (string[] args) {mycollection mycollection = new mycollection ();
        for (Integer i:mycollection) {System.out.print (i+ ""); }
    }
}

Printed: 78 59-7 15 29 10 48 2 4

Note: The foreach statement can be used for arrays or any other iterable, but the array is not a iterable, and this is something we have to pay attention to. Listiterator

Listiterator is a more powerful iterator that inherits the iterator interface. It can be used only for the access of various list classes , and for bidirectional movement . You can generate a listiterator at the beginning of the list by calling the Listiterator () method, and you can also create a listiterator at the beginning of the element that points to the list index n by calling the Listiterator (n) method. The following is the new method defined by Listiterator:

Hasprevious (): Detects if the container has a previous element, if any, returns true. It is mainly used for reverse iteration and Hasnext () just the opposite. Previous (): Gets the previous element of the container. This is mainly used for reverse iterations and next () just the opposite. Nextindex () and Previousindex (): Returns the index of the previous element and the last element in the container. Set (E): Replaces the element that is pointed to when the next or previous method is invoked. Must be called after the next or previous method. Add (E): Inserts an element into the container.

public static void display (Iterator<integer> it) {while (It.hasnext ()) {System.out.print (it.ne
        XT () + "");
    } System.out.println (); public static void Main (string[] args) {list<integer> ll = arrays.aslist (78, 94, 54, 12, 5, 69,-8, 4
        8, 48, 984, 14);
        Listiterator It=ll.listiterator ();
        Forward while (It.hasnext ()) {System.out.println (It.next () + "," +it.nextindex () + "," +it.previousindex ());
        } System.out.println ();
        Reverse while (it.hasprevious ()) {System.out.print (it.previous () + "");
        } System.out.println ();
        Gets the iterator It=ll.listiterator (3) that points to a specific index;
            while (It.hasnext ()) {it.next ();
        It.set (4);
    } System.out.println (LL); 
    /*output:78, 1, 0 94, 2, 1 54, 3, 2 12, 4, 3 5, 5, 4 69, 6, 5-8, 7, 6 48, 8, 7 48, 9, 8 984, 10, 9 14,11, 10 14 984 48 48-8 69 5 12, 54 94 [78, 78, 94, 54, 4, 4, 4, 4, 4, 4, 4] * * 

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.