Java thousand ask _06 data structure (012) _ How to iterate over an array

Source: Internet
Author: User

Click to enter _ more _java thousand ask

1. How to iterate through an array

When we work with arrays, we often use a for loop or a foreach loop to iterate because all the elements in the array are of the same type and the size of the array is known.
Learn what an array looks here: What is an array in Java
See the For loop here: How to Loop through Java

Use for loop traversal
 Public classTestarray { Public Static void Main(string[] args) {Double[] MyList = {1.9,2.9,3.4,3.5};//Print all the array elements       for(inti =0; i < mylist.length; i++) {System. out. println (Mylist[i] +" "); }//Summing all elements      DoubleTotal =0; for(inti =0; i < mylist.length;      i++) {total + = Mylist[i]; } System. out. println (" Total is"+ total);//Finding the largest element      Doublemax = mylist[0]; for(inti =1; i < mylist.length; i++) {if(Mylist[i] > max) max = mylist[i]; } System. out. println ("Max is"+ max); }}

This will produce the following results:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Traversing with a foreach loop

JDK 1.5 introduces a new for loop called a Foreach loop or an enhanced for loop that iterates through an array sequentially without using an indexed variable.

publicclass TestArray {   publicstaticvoidmain(String[] args) {      double[] myList = {1.92.93.43.5};      // Print all the array elements      for (double element: myList) {         System.out.println(element);      }   }}

This will produce the following results:
1.9
2.9
3.4
3.5

Java FAQ _06 data structure (012) _ How to iterate over an array

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.