Statements similar to foreach in Java

Source: Internet
Author: User

From: http://blog.csdn.net/mcy478643968/archive/2009/05/17/4194543.aspx

Different from C #, foreach is a keyword in C #. in Java, the foreach statement is a special simplified version of the for statement, but the foreach statement cannot completely replace the for statement, any foreach statement can be rewritten to the for statement version.

The expression of the foreach statement in Java:
For (element type T element variable X: traversing object OBJ ){
References the Java Statement of X;
}

Example:

/**
* The foreach statement outputs a one-dimensional array.
*/
Public void test1 (){
// Define and initialize an array
Int arr [] = {2, 3, 1 };
System. Out. println ("---- 1 ----");
For (int x: ARR ){
System. Out. println (x); // outputs the values of array elements one by one.
}

Public void listtoarray (){
// Create a list and add elements
List <string> List = new arraylist <string> ();
List. Add ("1 ");
List. Add ("3 ");

// Use the froeach statement to output the set Element
System. Out. println ("---- 2 ----");
For (string X: List ){
System. Out. println (X );
}

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.