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