Replace iterator
Let's start by recalling the use of iterators in Java, which can be used with the list and set sets of iterators. The reason is that they all implement the collection interface, and the collection interface has a parent interface called Iterable. Let's look at a case:
PublicClass Demo {@Test Public voidDemo () {List<String> List = NewArrayList<String>();List.Add"Hello");List.Add"World"); Iterator<String>Iterator= List.Iterator (); while(Iterator.Hasnext ()) {String string =Iterator.Next (); System.Out.printlnstring); } }}
After the Java 5 release, the enhanced for loop is provided to replace the original iterator. Let's look at the following code:
publicclass Demo { @Test publicvoiddemo() { new ArrayList<String>(); list.add("hello"); list.add("world"); forstring : list) { System.out.println(string); } }}
With the above two pieces of code, we can see that the output is exactly the same. However, in writing, strengthening the For loop is more concise.
Strengthening for role
In practical use, what are the functions of strengthening for loops? Let's discuss them separately.
- The first usage: can be used to loop through all the collections of the Iterable interface, such as the above case:
publicclass Demo { @Test publicvoiddemo() { new ArrayList<String>(); list.add("hello"); list.add("world"); forstring : list) { System.out.println(string); }}}
- Second usage: can be used for looping arrays.
publicclass Demo { @Test publicvoiddemo3() { "hello""world" }; forstring : arr) { System.out.println(string); } }}
Issues to be aware of
Having mastered the use of the For loop, let's think about what we need to pay attention to in the practical application of the For loop.
- When you iterate through an array or collection with the strengthen for loop, you cannot traverse a portion of the content only from beginning to end.
- You cannot get the index value of the current element when traversing an array or collection with the strengthen for loop.
- Strengthening the For loop is just one way to replace iterators.
Deep Enhancement for
Since the strengthen for loop can traverse all the implementations of the Iterable interface, then we can not customize a collection that implements the Iterable interface, and then use the enhanced for to traverse it?
Let's customize a collection class that implements the Iterable interface:
Public class Word implements iterable { PrivateString[] words; Public Word(String s) {words = S.split ("\\s+"); }@Override PublicIteratoriterator() {return NewIterator () {Private intindex =0; Public Boolean Hasnext() {returnIndex < words.length; } PublicObjectNext() {returnWords[index++]; } Public void Remove() {} }; }}
Then, we test:
publicclass Demo { @Test publicvoiddemo4() { new Word( "hello world javaWeb css html el jstl jsp servlet response"); for (Object obj : word) { System.out.println(obj); } }}
Reprint NOTE: Please indicate the author and the original link, thank you!
[Java5 new feature] enhanced for loop