微信扫一扫

028-83195727 , 15928970361
business@forhy.com

Java千百问_06数据结构(012)_如何遍历数组

java数组遍历,java数组循环,java数组获取值,数组如何遍历,fore-for数组2016-06-04

点击进入_更多_Java千百问

1、如何遍历数组

我们在处理数组时,经常使用for循环foreach循环进行遍历,因为数组中的所有元素类型相同并且数组的大小是已知的
了解什么是数组看这里:java中的数组是什么
了解for循环看这里:java中如何循环执行

使用for循环遍历
public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
      // Summing all elements
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // Finding the largest element
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}

这将产生以下结果:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

使用foreach循环遍历

JDK 1.5引入了一个新的for循环被称为foreach循环增强的for循环,它无需使用索引变量就能按顺序遍历数组。

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

这将产生以下结果:
1.9
2.9
3.4
3.5