您的位置 首页 java

Java|深入理解二维数组的声明与初始化

A two dimensional array is implemented as an array of one dimensional arrays. This is not as awful as you might think. It is an extension of what you already know about one dimensional arrays of objects. The declaration

二维数组 被实现为一维数组的数组。这并不像你想象的那么可怕。它是您已经知道的一维对象数组的扩展。例如下面二维数组声明:

 int[][] myArray; // 1.  

declares a variable myArray which in the future may refer to an array object. At this point, nothing has been said about the number of rows or columns.

声明一个变量myArray,该变量将来可能引用数组对象。在这一点上,关于行或列的数量还没有提到。

To create an array of 3 rows do this:

要创建包含3行的数组,请执行以下操作:

 myArray = new int[3][] ; // 2.  

Now myArray refers to an array object. The array object has 3 cells. Each cell may refer (in the future) to an array of int, an int[] object. However none of the cells yet refer to an object. They are initialized to null.

现在myArray引用了一个数组对象。数组对象有3个单元格。每个单元格可能(将来)引用一个int数组,即int[]对象。然而,还没有一个单元格指向某个对象。它们被初始化为null。

One way to create row 0 is this:

创建第0行的一种方法是:

 myArray[0] = new int[3] ; // 3.  

This creates a 1D array object and puts its reference in cell 0 of myArray. The cells of the 1D array are initialized to 0.

这将创建一个1D数组对象,并将其引用放在myArray的单元格0中。1D数组的单元格初始化为0。

A previously constructed 1D array can be assigned to a row:

可以将先前构造的一维数组分配给一行:

 int[] x = {0, 2};
int[] y = {0, 1, 2, 3, 4} ;
myArray[1] = x ;
myArray[2] = y ; // 4.  

The rows do not need to have the same number of cells.

行不需要具有相同数量的单元格。

(因为相当于C或C++在堆上的动态分配,几行,第行几列都随意。)

The preceding statements construct the 2D array step-by-step. Usually you would not do this.

前面的语句逐步构造2D数组。通常你不会这样做。

Java 的二维数组有点类似于C/C++的动态指针数组,不同的是,C++的二维动态数组是通过一维指针数组的每一个指针去指向一维数组。另外,Java数组是有初始化和边界检查的)

对于二维数组的长度,各维的长度都分别用 length ()方法来统计:

 class unevenExample3
{
    public  static   void  main( String[] arg )
    {
        // declare and construct a 2D array
        int[][] uneven =
        { { 1, 9, 4 },
        { 0, 2},
        { 0, 1, 2, 3, 4 } };
        // print out the array
        for( int row=0; row < uneven.length; row++ )
        {
            System.out.print("Row " + row + ": ");
            for( int col=0; col < uneven[row].length; col++ )
                System.out.print( uneven[row][col] + " ");
            System.out.println();
        }
    }
}  

-End-

文章来源:智云一二三科技

文章标题:Java|深入理解二维数组的声明与初始化

文章地址:https://www.zhihuclub.com/183315.shtml

关于作者: 智云科技

热门文章

网站地图