Lanson

V1

2022/11/13阅读：20主题：丘比特忙

# 二维数组

## 二、基本代码

``public class TestArray15{        public static void main(String[] args){                //定义一个二维数组：                int[][] arr = new int[3][];//本质上定义了一个一维数组，长度为3                                int[] a1 = {1,2,3};                arr[0] = a1;                                arr[1] = new int[]{4,5,6,7};                                arr[2] = new int[]{9,10};        }}``

## 三、四种遍历方式

``public class TestArray15{        public static void main(String[] args){                //定义一个二维数组：                int[][] arr = new int[3][];//本质上定义了一个一维数组，长度为3                                int[] a1 = {1,2,3};                arr[0] = a1;                                arr[1] = new int[]{4,5,6,7};                                arr[2] = new int[]{9,10};                                //读取6这个元素：                //System.out.println(arr[1][2]);                                //对二维数组遍历：                //方式1：外层普通for循环+内层普通for循环：                for(int i=0;i<arr.length;i++){                        for(int j=0;j<arr[i].length;j++){                                System.out.print(arr[i][j]+"\t");                        }                        System.out.println();                }                                //方式2：外层普通for循环+内层增强for循环：                for(int i=0;i<arr.length;i++){                        for(int num:arr[i]){                                System.out.print(num+"\t");                        }                        System.out.println();                }                                //方式3：外层增强for循环+内层增强for循环：                for(int[] a:arr){                        for(int num:a){                                System.out.print(num+"\t");                        }                        System.out.println();                }                                //方式4：外层增强for循环+内层普通for循环：                for(int[] a:arr){                        for(int i=0;i<a.length;i++){                                System.out.print(a[i]+"\t");                        }                        System.out.println();                }        }}``

## 四、二维数组的初始化方式

• 静态初始化

eg:

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

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

• 动态初始化

eg:

int[][] arr = new int[3][]; //本质上定义了一维数组长度为3，每个“格子”中放入的是一个数组

arr[0] = new int[]{1,2};

arr[1] = new int[]{3,4,5,6};

arr[2] = new int[]{34,45,56};

eg:

int[][] arr = new int[3][2];

``public class TestArray16{         public static void main(String[] args){                 int[][] arr = new int[3][2];                 //本质上：定义一维数组，长度为3，每个数组“格子”中，有一个默认的长度为2的数组：                 arr[1] = new int[]{1,2,3,4};                 //数组遍历：                 for(int[] a:arr){                         for(int num:a){                                         System.out.print(num+"\t");                         }                         System.out.println();                 }         } } ``

• 默认初始化

Java

V1

CSDN大数据领域博客专家