java 2D Array Specifies Different Length Instance Methods

  • 2021-09-05 00:04:28
  • OfStack

We know that the 2-dimensional array is based on the 1-dimensional array, and the dimension is increased. Then, in the actual use process, sometimes we need 2-dimensional arrays, which have different dimensions, which requires us to set them manually. Let's explore the method of changing the dimension length of 2-dimensional array, and show the code with examples.

Each element of a 1-D or 2-D array is a 1-D array, and these arrays are not of equal length. When you declare a 2-dimensional array, you can specify only the 1-dimensional size, leave the 2-dimensional size blank, and then specify arrays of different lengths. Note, however, that the 1 th dimension size cannot be vacant (you cannot specify only the number of columns but not the number of rows).


public class ArrayTest4
{
  public static void main(String[] args)
  {
    //2 Dimensional variable length array 
    int[][] a = new int[3][];
    a[0] = new int[2];
    a[1] = new int[3];
    a[2] = new int[1];
    //Error:  Can't vacate the first 1 Dimensional size 
    //int[][] b = new int[][3];
  }
}

2, 2-dimensional arrays can also be initialized at the time of definition, using the nesting of curly braces. At this time, the size of two dimensions is not specified, and array elements with different lengths can be generated according to the number of initialization values.


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

Instance extension:

Java 2-D array instances without specifying length


import java.util.*;
public class Tek
{
 public static void main(String[] args)
 { 
 int[][] a=new int[3][];
 a[0]=new int[3];// Equivalent to int[] a=new int[3]
 for(int i=0;i<a[0].length;i++)
 a[0][i]=i+1;
 
 a[1]=new int[4];
 for(int i=0;i<a[1].length;i++)
 a[1][i]=i+1;
 
 a[2]=new int[5];
 for(int i=0;i<a[2].length;i++)
 a[2][i]=i+1;
 
 
 for(int i=0;i<a.length;i++)
 {
 for(int j:a[i])
 System.out.print(j+" "); 
 System.out.println();
 
 } 
 
 }
}

Related articles: