The purpose of an iterator is to fetch the elements in the collection.
Iterator methods:
Hasnext () asks if there are elements that can be traversed. Returns true if there are elements that can traverse, otherwise false is returned.
Next () Gets the element ...
Remove () removes the last element returned by the iterator
Nosuchelementexception does not have an element exception.
Cause: No elements can be iterated ...
Import Java.util.arraylist;import Java.util.collection;import Java.util.iterator;public class Demo01 {public static void Main (string[] args) { Collection c1=new ArrayList (); C1.add ("Dog Doll"); C1.add ("The Dog Remains"); C1.add ("Iron egg");
C1.add ("Meimei"); Iterator it =c1.iterator (); while (It.hasnext ()) { System.out.println ("element is:" +it.next ());}}}
Output Result:
The element is: Dog doll
The element is: the dog left
Element is: Iron Egg
Elements are: Meimei
Q: Iterator() method return is an interface type, why can the interface call methods to use it?
A:Iterator actually returns an implementation class for the interface iterator.
Remove method: Removes the last element returned by the iterator
Import Java.util.arraylist;import Java.util.collection;import Java.util.iterator;public class Demo01 {public static void Main (string[] args) { Collection c1=new ArrayList (); C1.add ("Beijing"); C1.add ("Shanghai"); C1.add ("Guangzhou"); Iterator it =c1.iterator (); while (It.hasnext ()) { if ("Beijing". Equals (It.next ())) { it.remove (); } } System.out.println ("After removal:" +C1);} }
Output: After removal: [Shanghai, Guangzhou]
Package cn.itcast.list;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.ListIterator;
/*
Iterators are important when it comes to variable elements: when iterating over an element, the collection object is not allowed to change the number of elements in the collection, or if you need to add or remove methods that can only use iterators.
If you have used a collection object to change the number of elements in the collection, then a concurrentmodificationexception exception occurs.
In the process of iterating over an element: When the iterator is created to the end of the use.
*/
public class Demo5 {
public static void Main (string[] args) {
List List = new ArrayList ();
List.add ("Zhang San");
List.add ("John Doe");
List.add ("Harry");
Listiterator it = List.listiterator ();//Get to Iterator
/*while (It.hasnext ()) {
System.out.print (It.next () + ",");
It.add ("AA"); Adds an element to the current pointer to a position
List.add ("AA"); The Add method is to add an element to the end of the collection.
List.remove ("Zhang San");
}*/
List.add ("AA");
It.next ();
System.out.println ("\ r \ n elements of the collection:" + list);
}
}
Iterator to the Java collection