Java에서 2차원 배열을 선언하고 초기화하는 다양한 방법
다차원 배열 . 가장 일반적으로 사용되는 다차원 배열은 2차원 배열과 3차원 배열입니다. 더 높은 차원의 배열은 기본적으로 배열의 배열이라고 말할 수 있습니다. 2D 배열의 매우 일반적인 예는 체스 보드입니다. 체스판은 1×1 정사각형 상자 64개가 들어 있는 격자판입니다. 2D 배열도 비슷하게 시각화할 수 있습니다. 2D 배열에서 모든 요소는 행 번호 및 열 번호와 연결됩니다. 2D 배열의 요소에 액세스하는 것은 행 번호와 열 번호를 모두 사용하여 Excel 파일의 레코드에 액세스하는 것과 유사합니다. 2D 배열은 Tic-Tac-Toe 게임, 체스를 구현하거나 이미지 픽셀을 저장하는 동안에도 유용합니다.
Java에서 2차원 배열 선언:
2차원 배열은 다음과 같이 선언할 수 있습니다.
통사론:
data_type 배열_이름[][]; (또는) data_type[][] 배열_이름;
- data_type: Java는 정적으로 유형이 지정된 언어이기 때문에(즉, 변수에 값을 할당하기 전에 선언해야 함) 따라서 데이터 유형을 지정하면 허용할 요소의 유형이 결정됩니다. 예를 들어 정수 값만 저장하려면 데이터 유형을 int로 선언합니다. array_name: 2차원 배열에 부여되는 이름입니다. 예를 들어 과목, 학생, 과일, 학과 등
메모: data_type 뒤에 [ ][ ]를 쓰거나 2D 배열을 선언할 때 array_name 뒤에 [ ][ ]를 쓸 수 있습니다.
자바
// java program showing declaration of arrays> import> java.io.*;> > class> GFG {> > public> static> void> main(String[] args)> > {> > > int> [][] integer2DArray;> // 2D integer array> > String[][] string2DArray;> // 2D String array> > double> [][] double2DArray;> // 2D double array> > boolean> [][] boolean2DArray;> // 2D boolean array> > float> [][] float2DArray;> // 2D float array> > double> [][] double2DArray;> // 2D double array> > }> }> |
Java에서 2차원 배열을 초기화하는 다양한 접근 방식:
data_type[][] 배열_이름 = 새로운 data_type[no_of_rows][no_of_columns];
2D 배열의 총 요소는 (no_of_rows) * (no_of_columns)와 같습니다.
- no_of_rows: 배열의 행 수입니다. 예를 들어 no_of_rows = 3이면 배열에 3개의 행이 있습니다. no_of_columns: 배열의 열 수입니다. 예를 들어 no_of_columns = 4이면 배열에 4개의 열이 있습니다.
위의 배열 초기화 구문은 지정된 데이터 유형에 따라 모든 배열 요소에 기본값을 할당합니다.
다음은 2D 배열을 초기화하기 위한 다양한 접근 방식의 구현입니다.
접근법 1:
자바
// java program to initialize a 2D array> import> java.io.*;> > class> GFG {> > public> static> void> main(String[] args)> > {> > // Declaration along with initialization> > // 2D integer array with 5 rows and 3 columns> > // integer array elements are initialized with 0> > int> [][] integer2DArray => new> int> [> 5> ][> 3> ];> > System.out.println(> > 'Default value of int array element: '> > + integer2DArray[> 0> ][> 0> ]);> > > // 2D String array with 4 rows and 4 columns> > // String array elements are initialized with null> > String[][] string2DArray => new> String[> 4> ][> 4> ];> > System.out.println(> > 'Default value of String array element: '> > + string2DArray[> 0> ][> 0> ]);> > > // 2D boolean array with 3 rows and 5 columns> > // boolean array elements are initialized with false> > boolean> [][] boolean2DArray => new> boolean> [> 4> ][> 4> ];> > System.out.println(> > 'Default value of boolean array element: '> > + boolean2DArray[> 0> ][> 0> ]);> > > // 2D char array with 10 rows and 10 columns> > // char array elements are initialized with> > // 'u0000'(null character)> > char> [][] char2DArray => new> char> [> 10> ][> 10> ];> > System.out.println(> > 'Default value of char array element: '> > + char2DArray[> 0> ][> 0> ]);> > > // First declaration and then initialization> > int> [][] arr;> // declaration> > > // System.out.println('arr[0][0]: '+ arr[0][0]);> > // The above line will throw an error, as we have> > // only declared the 2D array, but not initialized> > // it.> > arr => new> int> [> 5> ][> 3> ];> // initialization> > System.out.println(> 'arr[0][0]: '> + arr[> 0> ][> 0> ]);> > }> }> |
메모: 2차원 배열을 초기화할 때 항상 첫 번째 차원(행 수)을 지정해야 하지만, 두 번째 차원(열 수) 제공은 생략될 수 있습니다.
아래 코드 조각에서는 열 수를 지정하지 않았습니다. 그러나 Java 컴파일러는 열 내부의 요소 수를 확인하여 크기를 조작할 만큼 똑똑합니다.
자바
import> java.io.*;> > class> GFG {> > public> static> void> main(String[] args)> > {> > // The line below will throw an error, as the first> > // dimension(no. of rows) is not specified> > int> [][] arr => new> int> [][> 3> ];> > > // The line below will execute without any error, as> > // the first dimension(no. of rows) is specified> > int> [][] arr => new> int> [> 2> ][];> > }> }> |
행 번호와 열 번호를 사용하여 2D 배열의 모든 요소에 액세스할 수 있습니다.
접근법 2:
아래 코드 조각에서는 행과 열의 수를 지정하지 않았습니다. 그러나 Java 컴파일러는 행과 열 내부의 요소 수를 확인하여 크기를 조작할 만큼 똑똑합니다.
자바
import> java.io.*;> > class> GFG {> > public> static> void> main(String[] args)> > {> > String[][] subjects = {> > {> 'Data Structures & Algorithms'> ,> > 'Programming & Logic'> ,> 'Software Engineering'> ,> > 'Theory of Computation'> },> // row 1> > > {> 'Thermodynamics'> ,> 'Metallurgy'> ,> > 'Machine Drawing'> ,> > 'Fluid Mechanics'> },> // row2> > > {> 'Signals and Systems'> ,> 'Digital Electronics'> ,> > 'Power Electronics'> }> // row3> > };> > > System.out.println(> > 'Fundamental Subject in Computer Engineering: '> > + subjects[> 0> ][> 0> ]);> > System.out.println(> > 'Fundamental Subject in Mechanical Engineering: '> > + subjects[> 1> ][> 3> ]);> > System.out.println(> > 'Fundamental Subject in Electronics Engineering: '> > + subjects[> 2> ][> 1> ]);> > }> }> |
산출
Fundamental Subject in Computer Engineering: Data Structures & Algorithms Fundamental Subject in Mechanical Engineering: Fluid Mechanics Fundamental Subject in Electronics Engineering: Digital Electronics
접근법 3:
게다가 배열의 각 요소를 개별적으로 초기화할 수도 있습니다. 아래 코드 조각을 살펴보세요.
자바
import> java.io.*;> import> java.util.*;> > class> GFG {> > public> static> void> main(String[] args)> > {> > int> [][] scores => new> int> [> 2> ][> 2> ];> > // Initializing array element at position[0][0],> > // i.e. 0th row and 0th column> > scores[> 0> ][> 0> ] => 15> ;> > // Initializing array element at position[0][1],> > // i.e. 0th row and 1st column> > scores[> 0> ][> 1> ] => 23> ;> > // Initializing array element at position[1][0],> > // i.e. 1st row and 0th column> > scores[> 1> ][> 0> ] => 30> ;> > // Initializing array element at position[1][1],> > // i.e. 1st row and 1st column> > scores[> 1> ][> 1> ] => 21> ;> > > // printing the array elements individually> > System.out.println(> 'scores[0][0] = '> > + scores[> 0> ][> 0> ]);> > System.out.println(> 'scores[0][1] = '> > + scores[> 0> ][> 1> ]);> > System.out.println(> 'scores[1][0] = '> > + scores[> 1> ][> 0> ]);> > System.out.println(> 'scores[1][1] = '> > + scores[> 1> ][> 1> ]);> > // printing 2D array using Arrays.deepToString() method> > System.out.println(> > 'Printing 2D array using Arrays.deepToString() method: '> );> > System.out.println(Arrays.deepToString(scores));> > }> }> |
산출
scores[0][0] = 15 scores[0][1] = 23 scores[1][0] = 30 scores[1][1] = 21 Printing 2D array using Arrays.deepToString() method: [[15, 23], [30, 21]]
접근법 4
2D 배열의 크기가 너무 큰 경우 배열 초기화에 위의 접근 방식을 사용하는 것은 지루한 작업이 될 수 있습니다. 효율적인 방법은 대규모 2D 배열의 경우 배열 요소를 초기화하기 위해 for 루프를 사용하는 것입니다.
자바
import> java.io.*;> > class> GFG {> > public> static> void> main(String[] args)> > {> > int> rows => 80> , columns => 5> ;> > int> [][] marks => new> int> [rows][columns];> > > // initializing the array elements using for loop> > for> (> int> i => 0> ; i for (int j = 0; j marks[i][j] = i + j; } } // printing the first three rows of marks array System.out.println('First three rows are: '); for (int i = 0; i <3; i++) { for (int j = 0; j System.out.printf(marks[i][j] + ' '); } System.out.println(); } } }> |
산출
First three rows are: 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6
메모: 우리는 arr을 사용할 수 있습니다. length 함수는 행의 크기(1차원)를 구하고 arr[0].length 함수는 열의 크기(2차원)를 구합니다.
접근법 5: (가변 배열)
모든 행의 열 수가 서로 다르기를 원하는 특정 시나리오가 있을 수 있습니다. 이러한 유형의 배열을 가변 배열(Jagged Array)이라고 합니다.
자바
import> java.io.*;> > class> GFG {> > public> static> void> main(String[] args)> > {> > // declaring a 2D array with 2 rows> > int> jagged[][] => new> int> [> 2> ][];> > > // not specifying the 2nd dimension,> > // and making it as jagged array> > // first row has 2 columns> > jagged[> 0> ] => new> int> [> 2> ];> > // second row has 4 columns> > jagged[> 1> ] => new> int> [> 4> ];> > // Initializing the array> > int> count => 0> ;> > for> (> int> i => 0> ; i // remember to use jagged[i].length instead of // jagged[0].length, since every row has // different number of columns for (int j = 0; j jagged[i][j] = count++; } } // printing the values of 2D Jagged array System.out.println('The values of 2D jagged array'); for (int i = 0; i for (int j = 0; j System.out.printf(jagged[i][j] + ' '); System.out.println(); } } }> |
산출
The values of 2D jagged array 0 1 2 3 4 5
두 개의 2D 배열을 추가하는 프로그램:
자바
import> java.io.*;> import> java.util.*;> > class> GFG {> > public> static> void> main(String[] args)> > {> > int> [][] arr1 = { {> 1> ,> 2> ,> 3> }, {> 4> ,> 5> ,> 6> } };> > int> [][] arr2 = { {> 4> ,> 5> ,> 6> }, {> 1> ,> 3> ,> 2> } };> > int> [][] sum => new> int> [> 2> ][> 3> ];> > > // adding two 2D arrays element-wise> > for> (> int> i => 0> ; i for (int j = 0; j 0].length; j++) { sum[i][j] = arr1[i][j] + arr2[i][j]; } } System.out.println('Resultant 2D array: '); for (int i = 0; i System.out.println(Arrays.toString(sum[i])); } } }> |
산출
Resultant 2D array: [5, 7, 9] [5, 8, 8]