Java provides a special iterator <<interface>>Iterator. We can implement the interface for a certain sequence to provide a standard Java iterator. The function after the Iterator interface is to "use" an iterator.
Document definition:
- Package ;
-
- publicinterface Iterator<E> {
-
- boolean hasNext();//Judge whether the next object element exists
-
- E next();
-
- void remove();
- }
Package ;
public interface Iterator<E> {
boolean hasNext();//Judge whether the next object element exists
E next();
void remove();
}
Java also provides an Iterable interface. The function after the Iterable interface is implemented is to "return" an iterator. The sub-interfaces that we commonly use to implement this interface are: Collection<E>, Deque<E>, List<E>, Queue<E>, Set<E>, etc. The iterator() method of this interface returns a standard Iterator implementation. Implementing this interface allows objects to be targets of Foreach statements. You can traverse your underlying sequence through Foreach syntax.
The Iterable interface contains an iterator() method that can generate iterator, and the Iterable interface is used by foreach to move in the sequence. Therefore, if any class that implements the Iterable interface is created, it can be used in the foreach statement.
- Document definition:
-
- Package ;
-
- import ;
- public interface Iterable<T> {
- Iterator<T> iterator();
- }
Document definition:
Package ;
import ;
public interface Iterable<T> {
Iterator<T> iterator();
}
- Simple example of using Iterator
-
- import .*;
-
- publicclass TestIterator {
-
-
- public static void main(String[] args) {
-
-
-
- List list=new ArrayList();
-
- Map map=new HashMap();
-
- for(int i=0;i<10;i++){
-
- (new String("list"+i) );
-
- (i, new String("map"+i));
-
- }
-
- Iterator iterList= ();//The List interface implements Iterable interface
-
- while(()){
-
- String strList=(String)();
-
- (());
-
- }
-
- Iterator iterMap=().iterator();
-
- while(()){
-
- strMap=()();
-
- (());
-
-
-
- }
-
- }
-
- }
-
- <span style="color: rgb(0, 0, 153); font-size: 18px;"> </span><span style="color: rgb(0, 0, 153); font-size: 18px;"></span>
Simple example of using Iterator
import .*;
public class TestIterator {
public static void main(String[] args) {
List list=new ArrayList();
Map map=new HashMap();
for(int i=0;i<10;i++){
(new String("list"+i) );
(i, new String("map"+i));
}
Iterator iterList= ();//List interface implements Iterable interface
while(()){
String strList=(String)();
(());
}
Iterator iterMap=().iterator();
while(()){
strMap=()();
(());
}
}
}
Interface Iterator will extend its functions according to the situation in different subinterfaces, such as ListIterator for List, which can only be used for access to various List classes. ListIterator can be moved in both directions. Addedprevious()etc.
3 Iterator and generic combination
Iterator can return such an Iterator object to any implementation class in the collection class. Can be applied to any class.
Because the types of objects that can be loaded by the collection class (List and Set, etc.) are uncertain, when taken out from the collection, they are all Object types and need to be forced to convert them when used, which will be very troublesome. Using generics means telling the collection in advance to determine the type to load the collection, so that it can be used directly without displaying type conversion. It is very convenient.
Relationship with Iterator
for each is a newly added loop structure in jdk5.0 that can be used to process each element in a collection without considering the set subscript.
The format is as follows
for(variable:collection){ statement; }
Define a variable to temporarily store each element in the collection and execute the corresponding statement (block). The collection must be an array or a class object that implements the lterable interface.
- The above example uses generics and forEach writing:
-
- import .*;
- public class TestIterator {
-
-
-
- public static void main(String[] args) {
-
-
-
- List<String> list=new ArrayList<String> ();
-
- for(int i=0;i<10;i++){
-
- (new String("list"+i) );
-
- }
-
- for(String str:list){
-
- (str);
-
- }
-
- }
The above example uses generics and forEach writing:
import .*;
public class TestIterator {
public static void main(String[] args) {
List<String> list=new ArrayList<String> ();
for(int i=0;i<10;i++){
(new String("list"+i) );
}
for(String str:list){
(str);
}
}
It can be seen that the advantage of using for each loop statement is that it is more concise and less prone to errors, and there is no need to care about the starting and ending values of the subscript.
forEach is not a keyword, keyword or for, statements are implemented by iterator. The biggest difference is that they are in the remove() method.
Generally, calling deletion and adding methods are methods of specific collections, such as:
List list = new ArrayList(); (...); (...);
However, if the remove() method of the collection is called during the loop, it will cause the loop to error becauseThe size of () changes during the loop, which leads to an error. Therefore, if you want to delete an element in a collection in a loop statement, you must use the iterator's remove() method, because its remove() method will not only delete elements, but also maintain a flag to record whether it is currently deleteable. For example, you cannot call its remove() method twice in a row, and there will be at least one call to the next() method before the call.
forEach is to make iterator loop access simple and easier to write. Of course, the functions are not very complete, so if there is a deletion operation, you should still use its original form.
4 Comparison between using for loop and using iterator
Everyone has their own efficiency
ArrayList is used to access randomly faster, while the get() method in the for loop uses the random access method. Therefore, in ArrayList, the for loop is faster
Using LinkedList is faster to access sequentially. The next() method in iterator uses the sequentially access method. Therefore, in LinkedList, iterator is faster to use.
From the perspective of data structure, for loops are suitable for accessing sequential structures, and can quickly obtain specified elements based on subscripts. Iterator is suitable for accessing chain structures, because iterators are positioned through next() and Pre(). They can access sets without order.
The advantage of using Iterator is that you can use the same method to traverse elements in the collection without considering the internal implementation of the collection class (as long as it implements an interface). If you use Iterator to traverse elements in the collection, once you no longer use List and instead use Set to organize data, the code that traverses the elements does not need to be modified. If you use for traversal, then all algorithms that traverse this set must be adjusted accordingly, because List is ordered, Set is unordered, and the structure is different, and their access algorithms are also different.