Java中一维,二维数组的静态和动态初始化

    xiaoxiao2022-07-04  106

    数组概述:

    数组可以看成是多个相同类型数据的组合,对这些数据的统一管理;

    数组变量属于引用数据类型,数组也可以看成是对象,数组中的每一个元素相当于该对象的成员变量;

    数组中的元素可以是任何数据类型,包括基本数据类型和引用数据类型;

    一维数组的声明:

    声明方式: 例如; int a [ ]  = new int [3];

    Java语言中 声明是不能指定其长度[数组中元素的个数];

    非法声明; int a [5];

    数组对象的创建:

     public  class Test {

       public static void main (String args[ ] ) {

         int [ ] s;

         s = new int [5];

         for(int i = 0; i < 5; i ++) {

         s[i] = 2 * i + 1;

         }

       }

    }

    一维数组初始化

    动态初始化:

    public class Test {

      public static void main (String args [ ] ) {

      int a [ ];

      a =  new int [3];

      //int a [ ] = {1,2,3};

      Date days [ ];

      days = new Date [3];

      days [0]  = new Date(1,4,20040);

      days [1]  = new Date(2,4,20040);

      days [2]  = new Date(3,4,20040);

      }

    }

    class Date {

      int year,month,day;

      Date (int y,int m,int d) {

        year = y; month = m; day = d;

      }

    }

    静态初始化

    public class Test {

      public static void mian (String args [  ] ) {

        int a[ ]  = new int [ ] {3,9,8};

        Date days[ ]  = {

        new Date(1,4,2004),

        new Date(2,4,2004),

        new Date(3,4,2004)

        };

      }

    }

    class Date {

      int year,month,day;

      Date(int y,int m,int d) {

        year  = y; month = m;day = d;

      }

    }

    二维数组

    二维数组可以看成数组为元素的数组,例如:

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

    二维数组初始化

    静态初始化:

      int intA [ ] [ ] = {{1,2},{2,3},{3,4,5}};

      int intB [ 3] [ 2] = {{1,2},{2,4},{4,5}};  非法

    动态初始化:

      int a [ ] [ ] = new int [3] [5];

      int b [ ] [ ] = new int [3] [ ];

      b[0] = new int [2];

      b[1] = new int [3];

      b[2] = new int [5];

    最新回复(0)