Java中的锯齿数组如何使用?示例

2021年3月20日17:16:49 发表评论 1,201 次浏览

先决条件:Java中的数组

锯齿状阵列是一个数组数组, 这样成员数组可以具有不同的大小, 即我们可以创建一个二维数组, 但每行中的列数可变。这些类型的数组也称为锯齿数组

以下是演示上述概念的Java程序。

// Program to demonstrate 2-D jagged array in Java
class Main
{
     public static void main(String[] args)
     {
         // Declaring 2-D array with 2 rows
         int arr[][] = new int [ 2 ][];
  
         // Making the above array Jagged
  
         // First row has 3 columns
         arr[ 0 ] = new int [ 3 ];
  
         // Second row has 2 columns
         arr[ 1 ] = new int [ 2 ];
  
         // Initializing array
         int count = 0 ;
         for ( int i= 0 ; i<arr.length; i++)
             for ( int j= 0 ; j<arr[i].length; j++)
                 arr[i][j] = count++;
  
         // Displaying the values of 2D Jagged array
         System.out.println( "Contents of 2D Jagged Array" );
         for ( int i= 0 ; i<arr.length; i++)
         {
             for ( int j= 0 ; j<arr[i].length; j++)
                 System.out.print(arr[i][j] + " " );
             System.out.println();
         }
     }
}

输出如下:

Contents of 2D Jagged Array
0 1 2 
3 4

以下是另一个示例, 其中第i行具有i列, 即, 第一行具有1个元素, 第二行具有两个元素, 依此类推。

// Another Java program to demonstrate 2-D jagged 
// array such that first row has 1 element, second
// row has two elements and so on.
class Main
{
     public static void main(String[] args)
     {
         int r = 5 ;
  
         // Declaring 2-D array with 5 rows
         int arr[][] = new int [r][];
  
         // Creating a 2D array such that first row
         // has 1 element, second row has two 
         // elements and so on.
         for ( int i= 0 ; i<arr.length; i++)
             arr[i] = new int [i+ 1 ];
  
         // Initializing array
         int count = 0 ;
         for ( int i= 0 ; i<arr.length; i++)
             for ( int j= 0 ; j<arr[i].length; j++)
                 arr[i][j] = count++;
  
         // Displaying the values of 2D Jagged array
         System.out.println( "Contents of 2D Jagged Array" );
         for ( int i= 0 ; i<arr.length; i++)
         {
             for ( int j= 0 ; j<arr[i].length; j++)
                 System.out.print(arr[i][j] + " " );
             System.out.println();
         }
     }
}

输出如下:

Contents of 2D Jagged Array
0 
1 2 
3 4 5 
6 7 8 9 
10 11 12 13 14

本文作者:

拉胡尔·阿格劳瓦尔(Rahul Agrawal)

。如果你喜欢lsbin并希望做出贡献, 那么你也可以写一篇文章并将你的文章邮寄到contribution@lsbin.org。查看你的文章出现在lsbin主页上, 并帮助其他Geeks。

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: