Enhanced for Loop

Source: Internet
Author: User
Enhanced for loop.

After checking on the Internet, the enhanced for loop is a new feature of java1.5. The so-called "enhanced for loop" mainly targets containers. When this feature is used, developers can hand over the logic of "traversing containers with iterator" to the compiler for processing.

For example, an old example:

String name [] = {"Zhang San", "Li Si", "Wang Wu "};

For (INT I = 0; I <name. length; I ++ ){

System. Out. println (name [I]);

}

The enhanced for loop can be written as follows:

String name [] = {"Zhang San", "Li Si", "Wang Wu "};

For (string STR: Name ){

System. Out. println (STR );

}

You can also traverse a two-dimensional array. Write the following statement:

String name [] [] = {"Zhang San", "Li Si", "Wang Wu" },{ "ZHANG Liu", "Li Qi", "Wang ba "}, {"Zhang JIU", "Li Shi", "Wang Xi "}};

For (string str1: Name ){

For (string str2: str1 ){

System. Out. println (str2 );

}

}

In fact, this feature should be generally combined with generics for the greatest benefit. Let's see how we used to traverse the collection class. A simple example:

Arraylist <string> arraylist = arraylist <string> ();

For (INT I = 0; I <10; I ++ ){

Arraylist. Add ("mybook" + I );

}

For (INT I = 0; I <arraylist. Size (); I ++ ){

System. Out. println (arraylist [I]);

}

After using the enhanced for loop, you can write it like this (similar to the above ):

Arraylist <string> arraylist = arraylist <string> ();

For (INT I = 0; I <10; I ++ ){

Arraylist. Add ("mybook" + I );

}

For (string STR: arraylist )[

System. Out. println (STR );

 

}

 

----- Transferred from Sina Blog

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.