Java for-each and for-each

Source: Internet
Author: User

Java for-each and for-each

For container classes such as ArrayList, we often need to traverse the elements one by one to perform corresponding operations on each element.

As I write more code, the common practice is to use the traditional method, similar to the array Traversal method, that is, to set an int variable in the for loop as the index, and then use the get method of the List, if you want to do what you want, you can do nothing.

Of course, occasionally I will write it a little simpler. I will use the for (element type variable name: Set) method, that is, directly specify the actual element type without indexing, and take the next element, in this way, you can write less code.

However, no matter which one is used, I have never considered using the iterator. Although this is often mentioned in the tutorial, I also know that it is used for traversal and deletion. Because I have never encountered any bottleneck in retrieving elements using methods similar to array traversal, I have never studied iterator, and I have always thought it is useless.

Recently, when studying the source code of ArrayList and javaslist, there is also a large section in the source code about Iterator, which makes me even more puzzled: since it is a dispensable alternative, why does the official team have to spend so much effort to describe it?

 

Until recently, I have read about the comparison between for-each and traditional for loops. Here is a sentence for me to review Iterator:

    Not only does the for-each loop let you iterate over collections and arrays,

It lets you iterate over any object that implements the Iterable interface.

This has to make me doubt: Do I know the collection class that I used to know is that the Iterable interface can be implemented by adding a colon to the for method?

  

After google, we can see that for-each is a simple writing method, which is actually implemented by the iterator internally!

The following code is taken from StackOverFlow.

  

List<String> someList = new ArrayList<String>();

 

Normally, use the for-each Traversal method:

 

for (String item : someList) {    System.out.println(item);}

The point is that the above simple sentence is automatically translated into the following section by the compiler during the compilation process. The actual execution is exactly the following section:

for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {    String item = i.next();    System.out.println(item);}

 

Therefore, in actual development, although standard Iterator is rarely used, the common for-each dark box operations are all Iterator!

One of the advantages of the for-each operation created by Java is that it simplifies code writing and reduces the number of variables.

In addition, it is very important to greatly reduce the misoperation during the traversal process. Think about it. If you get the element value of the current position in the for-each process, how can you add, delete, or modify the element value? The answer is no. However, using Iterator or index to write loops allows you to perform almost all addition, deletion, and modification operations. Therefore, it is safer to use for-each.

 

Of course, for-each also has a usage, that is, it is used in the traversal of ordinary arrays, and also carries out a dark box operation, that is, converting to index traversal.

int[] test = new int[] {1,4,5,7};for (int intValue : test) {    // do some work here on intValue}

  

Compile-time conversion:

 

int[] test = new int[] {1,4,5,7};for (int i = 0; i < test.length; i++) {    int intValue = test[i];    // do some work here on intValue}

 

 

Be sure to note that,For-each can only be used for: ① Iterable ② Array

That is, in addition to arrays, a general class can use for-each as long as the Iterable interface is implemented.

 

We can freely write a class for fun.

Import java. util. iterator; public class MyClass <E> implements Iterable <E> {private class MyIterator implements Iterator <E> {private int max = 10; private int cur = 0; @ Override public boolean hasNext () {if (cur <max) return true; else return false;} @ SuppressWarnings ("unchecked") @ Override public E next () {Object res = ++ cur; return (E) res ;}@ Override public void remove () {System. out. println ("index:" + cur + "deleted") ;};@ Override public Iterator <E> iterator () {return new MyIterator ();}}

 

Test

import java.util.Iterator;public class JavaMain {    public static void main(String[] args) {        MyClass<Integer> m = new MyClass<>();        for (Integer i : m) {            System.out.println(i);        }        System.out.println("-------------------------------------------");        for (Iterator<Integer> it = m.iterator();it.hasNext();) {            Integer val = it.next();            if (val % 3 == 0)                it.remove();        }    }    }

 

Output result:

12345678910 ----------------------------------------- index: 3 deleted index: 6 deleted index: 9 deleted

 

 

The MyClass class here has no practical significance. It is an incredible task to test it successfully...

 

References:

Http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work

Http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.