Java study notes two (two-dimensional array)

1, a two-dimensional array understood that: a two-dimensional array can be understood as a one-dimensional array arr1 as elements of another one-dimensional array of arr2. (From the point of view of the operating mechanism underlying array is not in fact a multi-dimensional array.)

arr = [[1,2,3],[9,8,7]]

2, using a two-dimensional array

  • 1, declare and initialize a two-dimensional array;
  • 2, two-dimensional array of elements specified reference position;
  • 3, the length of the two-dimensional array;
  • 4, traverse the two-dimensional array;
  • 5, two-dimensional array of default initialization value;
  • 6, two-dimensional array of memory parsing;

3, default initial values of the two-dimensional array: two-dimensional array of elements is divided into inner and outer element,

  • arr [1] for the outer element.
  • arr [1] [0] for the inner element.
  • A way for dynamic initialization: int [] [] arr = new int [3] [4]; initialization value is an address value of the outer element, the inner initialized with the same value of the one-dimensional array
  • For two dynamic initialized: int [] [] arr = new int [3] []; outer initialization is null; inner initialization value can not be invoked, otherwise an error

Code:

public class ArrayTest2 {
	public static void main(String[] args) {
		//1.二维数组的声明和初始化
		int[] arr = new int[]{1,2,3};//一维数组
		//静态初始化
		int[][] arr1 = new int[][]{{1,2,3},{4,5},{6,7,8}};
		//动态初始化1
		String[][] arr2 = new String[3][2];
		//动态初始化2
		String[][] arr3 = new String[3][];
		//错误的情况 
//		String[][] arr4 = new String[][4];
//		String[4][3] arr5 = new String[][];
//		int[][] arr6 = new int[4][3]{{1,2,3},{4,5},{6,7,8}};
		
		//也是正确的写法:
		int[] arr4[] = new int[][]{{1,2,3},{4,5,9,10},{6,7,8}};
		int[] arr5[] = {{1,2,3},{4,5},{6,7,8}}; //类型推断
		
		//2.如何调用数组的指定位置的元素
		System.out.println(arr1[0][1]);//2
		System.out.println(arr2[1][1]);//null
		
		arr3[1] = new String[4];
		System.out.println(arr3[1][0]);
		
		//3.获取数组的长度
		System.out.println(arr4.length);//3
		System.out.println(arr4[0].length);//3
		System.out.println(arr4[1].length);//4
		
		//4.如何遍历二维数组
		for(int i = 0;i < arr4.length;i++){
			
			for(int j = 0;j < arr4[i].length;j++){
				System.out.print(arr4[i][j] + "  ");
			}
			System.out.println();
		}
		
	}
}
Published 11 original articles · won praise 14 · views 5458

Guess you like

Origin blog.csdn.net/ssnszds/article/details/104296024