멋사 부트캠프/Java 프로그래밍

05. 배열[1차, 2차] & 객체 배열 활용

cTosMaster 2025. 3. 10. 19:35

1. 배열 [1차원 배열]

정의 : 같은 자료형(타입)의 데이터를 연속된 메모리 공간에 저장하는 자료구조

          배열은 인덱스를 사용하여 개별 요소에 접근할 수 있으며, 고정된 크기를 갖습니다.

 

int[] numbers = new int[5];

(int) 리터럴 값0 (int) 리터럴 값1 (int) 리터럴 값2 (int) 리터럴 값3 (int) 리터럴 값4

               [0]                             [1]                               [2]                          [3]                        [4]

 

numbers = &[배열 주솟값] 저장됨.

 

사용 예시)

public static void main(String[] args) {

		int[] ar = new int[] { 10, 20, 30, 40, 50 };
		System.out.println("ar의 요소의 개수 =" + ar.length);

		for (int i = 0; i < ar.length; i++) {
			System.out.printf("%5d", ar[i]);
		}

		ar = new int[] { 100, 200, 300 };

		System.out.println("\n ar의 재할당된  요소의 개수 =" + ar.length);

		for (int i = 0; i < ar.length; i++) {
			System.out.printf("%5d", ar[i]);
		}
}

 

 

2. 배열 [2차원 배열]

정의 : 행렬의 개념이 들어가며, 배열안의 값이 배열로 들어가는 이중 배열입니다.

 

int[][] matrix = new int[3][4];

{ 0, 1, 2, 3, 4 ...} 
[0] [1] [2] [3] [4]
{ 0, 1, 2, 3, 4 ...}
[0] [1] [2] [3] [4]
{ 0, 1, 2, 3, 4 ...}
[0] [1] [2] [3] [4]
{ 0, 1, 2, 3, 4 ...}
[0] [1] [2] [3] [4]
{ 0, 1, 2, 3, 4 ...}
[0] [1] [2] [3] [4]

                 [0]                             [1]                          [2]                              [3]                              [4]

 

좀 더 알기 쉽게 행렬로 표현하면, 

matrix { 

                { 0, 1, 2, 3, 4 },

                { 0, 1, 2, 3, 4 },

                { 0, 1, 2, 3, 4 },

                { 0, 1, 2, 3, 4 },

                { 0, 1, 2, 3, 4 }

}

matrix [행 번호] [열 번호] 

 

사용 예시)

public static void main(String[] args) {
        // 2차원 배열 초기화
        int[][] ar = {
            { 10, 10, 10, 10, 0 },
            { 30, 30, 30, 30, 0 },
            { 40, 40, 40, 40, 0 },
            { 50, 50, 50, 50, 0 },
            { 0,  0,  0,  0,  0 } // 합계를 저장할 행/열
        };

        // 초기 배열 출력
        System.out.println("== 초기 배열 ==");
        printArray(ar);

        // 행, 열, 대각선 합 계산
        calculateSums(ar);

        // 계산 후 배열 출력
        System.out.println("== 계산 후 ==");
        printArray(ar);
    }

    // 2차원 배열 출력 메서드
    public static void printArray(int[][] array) {
        for (int[] row : array) {   // 행 반복
            for (int num : row) {   // 열 반복
                System.out.printf("%5d", num);
            }
            System.out.println();   // 줄바꿈
        }
    }

    // 행 합, 열 합, 대각선 합 계산
    public static void calculateSums(int[][] array) {
        int size = array.length - 1; // 마지막 행과 마지막 열은 합계를 저장하는 부분

        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                array[i][size] += array[i][j];  // 행의 합
                array[size][j] += array[i][j];  // 열의 합
                if (i == j) {
                    array[size][size] += array[i][j];  // 대각선 합
                }
            }
        }
    }

 

3. 객체 배열

말그대로 객체 인스턴스를 저장하는 배열입니다.

Object, Double, Integer, 커스텀 객체 등...

객체를 저장하여 호출 할 수 있습니다. (실제로는 객체의 주솟값이 저장이됩니다.)

 

사용 예시)

public class U_Score {
	private String name;
	private int kor;
	private int eng;
	private int mat;
	
	public U_Score(String name, int kor, int eng, int mat) {
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.mat = mat;
	}
	
	public U_Score() {
		this("no-name", 50, 50, 50);
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
       .....
}

public static void main(String[] args) {
		//선언과 동시에 나열 생성
		U_Score[] score = new U_Score[] {
				new U_Score("홍길동", 1, 2, 3),
				new U_Score("정길동",3, 3, 3),
				new U_Score("박길동", 5, 5, 5)
		};
		
		for(U_Score res : score) {
			System.out.println(res);
		}
		
		System.out.println("박길동 찾아서 전체 점수를 100으로 세팅 후 출력하자.");
		for(U_Score res : score) {
			if(res.getName().trim().equals("박길동")) {
				res.setKor(100);
				res.setEng(100);
				res.setMat(100);
				System.out.println(res);
			}
		}
}