For-each loop

Source: Internet
Author: User

Are you tired of writing mechanical code every time you write a for loop, especially when you need to traverse arrays or collections, such:

 Public voidShowall (collection C ){
For(Iterator iter = C. iterator (); ITER. hasnext ();){
System. Out. println (ITER. Next (). tostring ());
}
}
 
 Public voidShowall (string [] SA ){
For(INT I = 0; I <SA. length; I ++ ){
System. Out. println (SA [I]);
}
}

This code is not only bloated, but also prone to errors (think about it if we accidentally forget to move the iterator or subscript, or accidentally move the subscript in the loop body, it may be worse: A logical judgment is made in the loop body, which further affects the subscript or iterator location. There are many similar examples .) Why can't the compiler help us? In 5.0, we can write as follows:

 Public voidShowall (collection C ){
For(Object OBJ: C ){
System. Out. println (obj. tostring ());
}
}
 
 Public voidShowall (string [] SA ){
For(String STR: SA ){
System. Out. println (STR );
}
}

This code is clearer and more concise, isn't it? (Is it a bit like C # foreach ?) With generics, we can even make the first method more beautiful:

 Public voidShowall (collection <string> C ){
For(String STR: C ){
System. Out. println (STR );
}
}

With generics and enhanced for loops, we don't have to worry about the annoying for loop expressions and nesting in most cases. The following are exceptions: When you need to access iterator and the lower mark in the loop body, for example, when you need to remove or modify elements in the set or array.

Continued ....

Suppose we want to traverse a set to process the elements. The typical code is:
Void processall (collection C ){
For (iterator I = C. iterator (); I. hasnext (){
Myclass myobject = (myclass) I. Next ();
Myobject. Process ();
}
}
With the for-each loop, we can rewrite the code,
Void processall (collection <myclass> C ){
For (myclass myobject: C)
Myobject. Process ();
}
This code is much clearer than above and avoids forced type conversion.

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.