For-each of Java Black-out operation

Source: Internet
Author: User
Tags iterable

For our commonly used container classes such as ArrayList, it is often necessary to iterate through the elements inside to perform the corresponding operations on each element.

As I write a lot of code, the usual practice is to use the traditional, similar to the array traversal method, that is, set an int variable as the index in the for loop, and then use the Get method of the list, do what you want to do, do not encounter anything can not do.

Of course, occasionally I would write simple, with a for (element type variable Name: Collection) method, that is, without an index, directly specify the actual element type, remove an element, so that you can write less one line of code.

But in either case, I have not considered using iterators iterator, although the tutorial often mentions this thing, I also know that this is used to traverse, by the way delete operations. Because using a similar array traversal method to take elements never encountered a bottleneck, it has never studied iterator, and has always felt that this is a non-egg use of things.

Recently in the study of ArrayList and LinkedList source code, there are a lot of source code is about iterator, which makes me even more puzzled: since it is a dispensable alternative to the things, why the authorities have to pay so much strength to describe it?

Until recently read "effective Java", read a section about the For-each and the traditional for loop comparison, inside there is a sentence let me re-examine iterator:

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

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

This has to make me wonder: do I know that the collection class, is because the implementation of the Iterable interface, you can use for the way to add a colon?

  

Google a bit, sure enough, for-each such a concise way of writing, the inside incredibly is using an iterator to achieve!

The following code is excerpted from StackOverflow

  

New Arraylist<string> ();

Normal use of For-each traversal method:

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

The point is, the above simple sentence, in the compilation process, the compiler automatically translated into the following paragraph, the actual execution of the time is the following:

 for (Iterator<string> i = somelist.iterator (); I.hasnext ();) {    = i.next ();    SYSTEM.OUT.PRINTLN (item);}

Therefore, in the actual development, although materializing rarely use the standard quasi-iterator, but the common for-each of the black-box operation is iterator!

Java creates For-each operations, one of the benefits of course is to simplify the writing of the Code, reducing the number of variables.

It is also important to significantly reduce the error in the traversal process. Think about it, if you get the value of the element in the current position in the For-each process, what can you do to add, delete, or modify the element value? The answer is no. However, using iterator or index to write loops, you can make almost all the additions and deletions. So the use of For-each to operate more secure.

Of course, For-each also has a usage that is used in the traversal of a normal array, in which there is also a black-box operation, that is, the traversal of the index.

int New int [] {1,4,5,7};  for (int  intvalue:test) {    // do some work here on Intvalue}

  

Compile-time conversions to:

int New int [] {1,4,5,7};  for (int i = 0; i < test.length; i++) {    int intvalue = test[i];     // Do some work here on Intvalue}

It is important to note thatFor-each can only be used for: ①iterable② arrays

That is, in addition to arrays, the general class as long as the implementation of the Iterable interface can be used For-each

We can write a class to play.

ImportJava.util.Iterator; Public classMyclass<e>ImplementsIterable<e>{        Private classMyiteratorImplementsIterator<e> {                Private intmax = 10; Private intCur = 0; @Override Public BooleanHasnext () {if(Cur <max)return true; Else                return false; } @SuppressWarnings ("Unchecked") @Override PublicE Next () {Object res= ++cur; return(E) res; } @Override Public voidRemove () {System.out.println ("Index:" +cur+ "was deleted");    }            }; @Override PublicIterator<e>iterator () {return NewMyiterator (); }    }

Under test

ImportJava.util.Iterator; Public classJavamain { Public Static voidMain (string[] args) {MyClass<Integer> m =NewMyclass<>();  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 deletedIndex: 6 deleted index:9 deleted

Our MyClass class here does not have any practical significance, actually the experiment succeeds, is really an incredible thing ...

Resources:

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

For-each of Java Black-out operation

Related Article

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.