[New Features of Java 5] Enhance the For Loop
Replacement iterator
Let's first recall the usage of the iterator in Java. You can use the List and Set sets of the iterator. 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:
public class Demo { @Test public void demo() { List
list = new ArrayList
(); list.add(hello); list.add(world); Iterator
iterator = list.iterator(); while (iterator.hasNext()) { String string = iterator.next(); System.out.println(string); } }}
After Java 5, it provides enhanced For loop to replace the original iterator. Let's look at the following code:
public class Demo { @Test public void demo() { List
list = new ArrayList
(); list.add(hello); list.add(world); for (String string : list) { System.out.println(string); } }}
The above two pieces of code show that the output results are exactly the same. However, in terms of writing, enhancing the For loop is more concise.
Enhance the For Function
In actual use, what are the functions of enhancing the For loop? Let's discuss it separately.
First, it can be used to implement all the sets of the Iterable interface cyclically. For example, in the above case:
public class Demo { @Test public void demo() { List
list = new ArrayList
(); list.add(hello); list.add(world); for (String string : list) { System.out.println(string); }}}
Second usage: it can be used for loop arrays.
public class Demo { @Test public void demo3() { String[] arr = { hello, world }; for (String string : arr) { System.out.println(string); } }}
Notes
After understanding how to enhance the For loop usage, let's take a look at the following. What problems need to be paid attention to in the practical use of the For Loop enhancement?
When using a For loop to traverse an array or set, only partial content can be traversed from start to end. The index value of the current element cannot be obtained when the array or set is traversed through the enhanced For loop. Reinforcing the For loop is only a replacement method of the iterator. Enhanced
Since enhanced For loops can traverse all sets that implement the Iterable interface, can we customize a set that implements the Iterable interface and then use enhanced For traversal?
Next we will define a collection class that implements the Iterable interface:
public class Word implements Iterable { private String[] words; public Word(String s) { words = s.split(\s+); } @Override public Iterator iterator() { return new Iterator() { private int index = 0; public boolean hasNext() { return index < words.length; } public Object next() { return words[index++]; } public void remove() {} }; }}
Then, let's test:
public class Demo { @Test public void demo4() { Word word = new Word( hello world javaWeb css html el jstl jsp servlet response); for (Object obj : word) { System.out.println(obj); } }}