Java for each loop array object traversal

Source: Internet
Author: User

Java for each loop array object traversal

Syntax

For (type itr-var: iterableobj) statement-block

View traversal array instances

Public class mainclass {
Public static void main (string args []) {
Int nums [] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
For (int x: nums ){
System. out. print (x + "");
X = x * 10; // no effect on nums
    }
  
System. out. println ();

For (int x: nums)
System. out. print (x + "");

System. out. println ();
  } 
}


Output

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10


Traverse enum objects

Public class mainclass {
Enum season {
Spring, summer, fall, winter
  }

Public static void main (string [] args ){
For (season: season. values ()){
System. out. println ("the season is now" + season );
    }
  }
}

Result

The season is now spring
The season is now summer
The season is now fall
The season is now winter

Traverse arraylist

Import java. util. arraylist;
 
Public class mainclass {
   
Public static void main (string args []) {
Arraylist <double> list = new arraylist <double> ();

List. add (1, 10.14 );
List. add (1, 20.22 );
List. add (1, 30.78 );
List. add (1, 40.46 );

Double sum = 0.0;
For (double itr: list)
Sum = sum + itr;
System. out. println (sum );
 
  }
}

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.