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