본문 바로가기

프로그래밍 공부/Java

Java - 배열

배열은 동일한 자료형으로 선언된 데이터 공간을 메모리 상에서 연속적으로 나열해 데이터 관리의 효율성을 높이는 것이다. JavaScript와는 다르게 Java는 동일한 자료형을 배열로 만드는게 일반적이다. 배열에는 같은 타입의 데이터를 연속된 공간에 나열시키고 각 데이터에 인덱스(index)를 부여해 놓은 자료구조이다.

배열의 선언

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
    public static void main(String[] args) {
        // int(정수) 타입 배열 선언한다.
        int[] array1;
        int array2[];
 
        // 배열 생성후 초기화하면 배열의 주소가 할당된다.
        int[] array3 = new int[8]; // 초기값은 0이다.
        String array4 = new String[8]; // 초기값은 ""이다.
 
        // 배열 선언만 하고, 나중에 초기화를 할 수 있다.
        int[] array5;
        array5 = new array[8];
    };
};
cs

배열의 선언은 위와 같은 방법으로 할 수 있다.

int array[] = new int[8];
               
[0] [1] [2] [3] [4] [5] [6] [7]

배열을 선언하고 크기를 할당하면 위와 같은 배열의 index가 부여된다.

배열의 변수는 참조변수에 속한다. 배열도 객체이며 힙 영역에 생성되고 배열의변수는 힙 영역의 배열 객체를 참조한다. new를 사용하지 않는다면 해당 배열은 null값을가지고 null값을 가진 상태에서 배열을 활용하려한다면 NullPointerException 오류가 발생한다.

이중 배열(또는 이차원 배열)

이중 배열은 JavaScript와 비교하면 배열안에 배열을 말한다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
    public static void main(String[] args) {
        // 이중 배열 선언
        int[][] array = new int[5][10];
 
        // 이중 배열의 초기화
        int[][] array = {   {1,2,3,4,5,6,7,8,9,10},
                            {2,3,4,5,6,7,8,9,10,11},
                            {3,4,5,6,7,8,9,10,11,12},
                            {4,5,6,7,8,9,10,11,12,13},
                            {5,6,7,8,9,10,11,12,13,14}
        };
    };
};
cs

위의 array 배열은 5행 10열의 배열이다. 10의 크기를 가진 배열이 5개 있다고 생각하면 된다.

[0][0] [0][1] [0][2] [0][3] [0][4] [0][5] [0][6] [0][7] [0][8] [0][9]
[1][0] [1][1] [1][2] [1][3] [1][4] [1][5] [1][6] [1][7] [1][8] [1][9]
[2][0] [2][1] [2][2] [2][3] [2][4] [2][5] [2][6] [2][7] [2][8] [2][9]
[3][0] [3][1] [3][2] [3][3] [3][4] [3][5] [3][6] [3][7] [3][8] [3][9]
[4][0] [4][1] [4][2] [4][3] [4][4] [4][5] [4][6] [4][7] [4][8] [4][9]

int[][] array = new int[5][10]의 구조는 위와 같다고 볼 수 있다.

다중 배열(또는 다차원 배열)

하나의 배열은 2, 3 혹은 그 이상의 다중 배열(또는 다차원 배열)을 가질 수 있다. 이중 배열(이차원 배열)이상을 갖는 배열을 다차원 배열이라고 한다. 삼중 배열(삼차원 배열)은 육면체로 그릴 수 있다. 하지만 그 이상의 배열은 그림으로 나타내기 어렵다. 이중 배열은 매우 일반적이지만 프로그램에서 다중 배열은 조심해서 사용해야 한다. 여러 레벨에서 방대한 양의 정보를 다루게 되면 관리가 힘들기 때문이다.

여러가지 배열 사용방법

예제 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Main {
    public static void main(String[] args) {
        int[][] ar = new int[4][5];
        
        for(int i = 0, v = 1; i < 5; i++) {
            for(int j = 0; j < 4; j++) {
                ar[j][i] = v++;
            }
        }
        for(int i = 0; i < 4; i++) {
            for(int j = 0; j < 5; j++) {
                System.out.printf("%2d ", ar[i][j]);
            }
            System.out.println();
        }
    };
};
cs

예제 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class Main {
    public static void main(String[] args) {
        // 2차원 배열 선언 -> 초기화
        int[][] ar1 = { 
            {123}, 
            {456
        };
        
        // 3차원 배열 선언 -> 초기화
        int[][][] ar2 = {
                {
                    {123},
                    {456}
                },
                {
                    {789},
                    {101112}
                }
        };
        for(int i = 0; i < ar1.length; i ++) {
            for(int j = 0; j < ar1[0].length; j++) {
                System.out.print(ar1[i][j] + " ");
            }
            System.out.println();
        }
        System.out.println();
        
        for(int i = 0; i < ar2.length; i++) {
            for(int j = 0; j < ar2[0].length; j++) {
                for(int k = 0; k < ar2[0][0].length; k++) {
                    System.out.print(ar2[i][j][k] + " ");
                }
                System.out.println();
            }
            System.out.println();
        }
    };
};
cs

예제 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Main {
    public static void main(String[] args) {
        int[][][] a = new int [3][2][3];
        
        for(int i = 0, v = 1; i < a.length; i++) {
            for(int j = 0; j < a[i].length; j++) {
                for(int k = 0; k < a[i][j].length; k++) {
                    a[i][j][k] = v++;
                }
            }
        }
        for(int[][] is : a) {
            for(int[] is2 : is) {
                for(int is3 : is2) {
                    System.out.printf("%2d ", is3);
                }
                System.out.println();
            }
            System.out.println();
        }
    };
};
cs

예제 4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int stN;
        int tot = 0;
        
        System.out.print("입력받을 인원 수를 입력 : ");
        stN = scanner.nextInt();
        String[] name = new String[stN];
        int[] n = new int[stN];
        int[] sc = new int[stN];
        System.out.println("성명, 학번, 점수를 입력하시오.\n\n");
        
        for(int i = 0; i < stN; i++) {
            System.out.print("성명 : ");
            name[i] = scanner.next();
            System.out.print("학번 : ");
            n[i] = scanner.nextInt();
            System.out.print("점수 : ");
            sc[i] = scanner.nextInt();
            tot += sc[i];
            System.out.println("\n");
        }
        System.out.printf("%5s %5s %5s\n""성 명""학 번""점 수");
        for(int i = 0; i < stN; i++) {
            System.out.printf("%3s %4d %3d", name[i], n[i], sc[i]);
        }
        System.out.printf("총점 : %d, 평균 : %d", tot, tot/stN);
    };
};
cs