The iterator interface in Java

Source: Internet
Author: User

Iterator interface

The iterator interface is also a member of the Java Collection framework, but it is not the same as the collection of the collection series, the map series: The collection collection, the Map series collection is mainly used for other objects,  The iterator is used primarily to traverse (that is, iterate) the elements in the collection collection, and iterator objects are also known as iterators.    The following 4 methods are defined in the iterator interface: –boolean hasnext (): Returns True if the iterated collection also does not traverse the element.    –object Next (): Returns the next element in the collection. –void Remove (): Removes the element returned by the previous next method in the collection –void foreachremaining (Consumer action), which is the default method added by Java 8 for iterator. The method can use a lambda expression to iterate over the collection element.
Import java.util.*;p ublic class iteratortest{public static void Main (string[] args) {//create collection, add element code same as previous program collection Books = new HashSet (); Books.add ("Lightweight Java EE Enterprise Application Combat") Books.add ("Crazy Java Handout"); Books.add ("Crazy Android Handout");// Gets the iterator that corresponds to the books collection iterator it = Books.iterator (); the while (It.hasnext ())) {//It.next () method returns a data type of type object, so you need to force the type conversion string Book = (String) it.next (); System.out.println (book), if (Book.equals ("Crazy Java Handout")) {//Remove the element returned from the previous next method from the collection It.remove ();} Assigning a value to a book variable does not change the collection element itself book = "Test string";   ①}SYSTEM.OUT.PRINTLN (books);}}

  

The iterator interface 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.