Java中的数组

一、数组是对象 

  数组是指具有相同类型数据的集合,一般具有固定长度,在内存中占据连续的存储空间。

  在Java中数组不仅具有自己的属性,也有一些方法可以被调用,从这个角度讲,数组是对象。可以通过instanceof来判断数组的类型,例如:

1 public static void main(String[] args) {
2         int [] a={1,2};
3         if(a instanceof int[]){
4             System.out.println(" the type of a is int[]");
5         }
6     }

    结果:

 the type of a is int[]

二、数组的声明及初始化 

  1.一维数组的声明

    type  arrayName[ ]  或  type  [ ]  arrayName

    其中,type既可以是基本的数据类型,也可以是类。arrayName表示数组的名称。

    在Java语言中,与C语言不同的是,数组被创建后会根据数组存放的数据类型初始化成相对应的初始值(例如,int类型初始化为0,对象会初始化为null)。另一个不同点是Java数组在定义时,并不会给数组元素分配存储空间,因此[ ]中不需要指定数组的长度。

    

    一维数组的初始化

1      int []a=new int [5]; //动态创建了一个包含5个整形值的数组,默认初始化为0;
2         int []b={1,2,3,4,5}; //声明了一个数组类型变量并初始化
3         
4         int []c;  //声明一个数组类型对象a
5         c=new int [3];  //给数组a申请可以存放3个int类型大小的空间,默认值为0
6         
7         int []d;  //声明一个数组类型对象a
8         d=new int[]{2,3,4,5};  //给数组申请空间,并初始化

    不要静态初始化和动态初始化同时使用,也就是说不要再进行数组初始化时,既指定数组长度,也为每个数组元素分配初始值。

  2.二维数组的声明

    type  arrayName[ ][ ];

    type  [ ]arrayName[ ];

    type [ ][ ]arrayName;

    需要注意的是,在声明二维数组时,其中的[ ]必须为空。

    二维数组可以通过new关键字来给数组申请存储空间,形式如下:

        type arrayName[] [] = new  type  [ 行数 ] [ 列数 ]

        但要注意在Java中采用上述方法声明二维数组时,必须要声明行数,列数可以不声明,示例:

        int a[][]=new int [2][];   //true
        int b[][]=new int [2][3];  //true
        int c[][]=new int [][4];   //false

  

   二维数组初始化   

    二维数组可以用初始化列表的方式来进行初始化,其一般形式为:

        type arrayName[] [] = {{c11,c12,c13},{c21,c22,c23},{c31,c32,c33}};

    与C语言不通的是,在Java语言中,二维数组的第二魏长度可以不同,例如:

1        int [][] arr={{1,2},{3,4,5}};
2         
3        int [][]a=new int[2][];
4        a[0]=new int[]{1,2};
5        a[1]=new int[]{7,8,9};

  

  二维数组的遍历

 1   public static void main(String[] args) {
 2         int [][]a=new int[2][];
 3         a[0]=new int[]{1,2};
 4         a[1]=new int[]{7,8,9};
 5         for (int i = 0; i < a.length; i++) {
 6             for (int j = 0; j < a[i].length; j++) {
 7                 System.out.print(a[i][j]+" ");
 8             }
 9         }
10     }

    输出结果:

          1 2 7 8 9 
原文地址:https://www.cnblogs.com/alternative/p/7512155.html