Java数组的定义与遍历方法

2019-02-21  本文已影响0人  夜阑w

一、定义

数组是有序数据的集合,数组中的每个元素具有相同的数组名和下标来做唯一标识。

注意:

  1. 数组长度一旦确定无法更改。

  2. 数组里的数据必须是相同类型或自动向上转型后兼容的类型。

声明数组:

int arrayDemo[];
int[] score;

创建数组:

int[] score = new int[3];
int score[]={2,5,6,4,6,7}; 

二、遍历方法

1、根据索引通过循环遍历

public class Test {
    public static void main(String[] args) {
        int score[] = {43,34,5,66,12};
        int max;
        max = score[0];
        for (int i = 0; i < score.length; i++) {
            if (score[i]>max) {
                max = score[i];
            }
        }
        System.out.println("最大值:"+max); //66
    }
}

2、foreach循环
foreach循环能够在不使用索引变量的情况下顺序遍历整个数组。
语法:

for(元素类型t 元素变量x : 遍历对象obj){ 
     引用了x的java语句; 
} 

例子:

public class Test {

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

      for (double element: myList) {
         System.out.println(element);
      }
   }
}

注意:foreach 循环时,不要对循环变量赋值。如果要在遍历时对数组元素进行赋值,那就应该根据数组元素的索引来进行遍历。

上一篇下一篇

猜你喜欢

热点阅读