1. 概念

         同一种类型数据的集合。其实数组就是一个容器。  

2. 数组的好处

          可以自动给数组中的元素从0开始编号,方便操作这些元素。

3. 格式1

      元素类型[] 数组名 = new 元素类型[元素个数或数组长度];

            int[] arr = new int[5];

4. 格式2

        元素类型[] 数组名 = new 元素类型[]{元素,元素,……};

              int[] arr = new int[]{3,5,1,7};

              int[] arr = {3,5,1,7};

 

        元素类型[] 数组名 = new 元素类型[元素个数或数组长度];

        //int x = 4;//一个数据。        
        //new :用于创建实体的关键字
        int[] arr = new int[3];
        //定义了一个int类型元素数组类型的变量 arr,
        //通过new关键字创建了一个数组实体,该实体中可以存储3个int类型的元素。


数组在内存的分配

    请看附件


数组的常见问题

//数组操作常见问题。
 
1. //ArrayIndexOutOfBoundsException:数组角标越界异常,发生在运行时期
    int[] arr = new int[3];
    //System.out.println(arr[3]);。
    //当访问到不存在的角标时,就会发生该异常。
 
2. //NullPointerException 空指针异常。
    arr = null;
    System.out.println(arr[1]);
    //当引用(arr)没有任何实体指向时,还在使用其操作实体,就会发生该异常。


举例,数组的常见操作-最值

public static int getMax(int[] arr)
{
    //1,定义变量,记录较大的值。
    int max = arr[0];//初始化是数组中的任意一个元素
    //2,遍历数组。
    for (int x=1; x<arr.length ;x++ )
    {
        //3,进行判断比较。
        if(arr[x]>max)
            max = arr[x];
     }
      return max;
  }

 
 //第二种最大值。
public static int getMax2(int[] arr)
{
    int maxIndex = 0;   //初始化为数组中任意一个角标。
    for (int x=0; x<arr.length ;x++ )
    {
        if(arr[x]>arr[maxIndex]){
         maxIndex = x;
        }
}