Iterator iterators in Java

Source: Internet
Author: User

The iterator method of collection returns an object that implements a iterator interface

The iterator interface contains three methods:

1) E Next ()

2) Boolean hasnext ()

3) void Remove

Specific usage:

Iterator<integer> integers=collection.iterator ();          while (Integers.hasnext ()) {            System.out.print (Integers.next ()+ "");        }

You can determine whether the end of the collection is reached by calling Hasnext ()

Call the next () method to return the element that is accessed

However, the above method can also be implemented through a Foreach loop

 for (Integer i:collection) {            System.out.print (i+ "");        }

The compiler simply translates a foreach loop into a loop with an iterator

The foreach use is conditional, that is, it must work with an object that implements the Iterable interface, and the collection interface extends the Iterable interface, so the collection can use the Foreach Loop

Iterator: The ability to separate the traversal sequence from the underlying structure of the sequence, through which it unifies the access to the container

 Public classaddinggroups { Public Static voidDisplay (iterator<string>iterator) {         while(Iterator.hasnext ()) {String s=Iterator.next (); System.out.print (S+" "+" ");    } System.out.println (); }     Public Static voidMain (string[] args) {List<String> list1=NewArraylist<> (Arrays.aslist ("A", "B", "C")); List<String> list2=NewLinkedlist<> (Arrays.aslist ("D", "E", "F")); Set Set1=NewHashset<> (Arrays.aslist ("G", "H", "I")); Set Set2=NewTreeset<> (Arrays.aslist ("J", "K", "L"));       Display (List1.iterator ());       Display (List2.iterator ());       Display (Set1.iterator ());    Display (Set2.iterator ()); }}

The iterator can be used regardless of the type information of the collection

Iterator iterators in Java

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.