2024.08.28 - Java 04 배열

한덕용·2024년 8월 29일

chunjaeFullstack

목록 보기
12/14

배열




배열이란?

여러 값들을 모은 자료형

배열은 왜 써야 할까?

  • 배열은 동일한 자료형의 변수를 한꺼번에 순차적으로 관리할 수 있다.


배열 선언과 초기화

// 1차원 배열

// 크기 할당과 초기화 없이 배열만 선언
int[] arr; // 이걸 많이 사용함.
// or
int arr[];


// 선언과 동시에 배열 크기 할당
int[] arr = new int[3];

String[] arr = new String[3];

// 기존 배열의 참조 변수에 초기화 할당하기
int[] arr;

arr = new int[5]; //5의 크기를 가지고 초기값 0으로 채워진 배열 생성

// 선언과 동시에 배열의 크기 지정 및 값 초기화
int[] arr = {1, 2, 3};
// or
int[] arr = new int[]  {1, 2, 3};

참고로 기본타입(Primitive type)의 배열인 경우 초기값을 가지고 있는 반면에(int = 0) 참조타입(Reference type)의 배열을 선언했을 경우 배열내 엘리먼트의 초기값이 null이다.


// 2차원 배열

// 크기 할당과 초기화 없이 배열만 선언
int[][] arr; // 이걸 많이 사용함.
// or
int arr[][];


// 선언과 동시에 배열 크기 할당
int[][] arr = new int[3][4]; // 3x4 크기의 배열 선언 (모든 값은 0으로 초기화)

// 각 행의 길이가 다른 배열도 선언 가능
int[][] arr = new int[3][]; // 열의 크기는 아직 할당하지 않음
arr[0] = new int[2]; // 첫 번째 행은 크기 2
arr[1] = new int[3]; // 두 번째 행은 크기 3
arr[2] = new int[4]; // 세 번째 행은 크기 4

// 선언과 동시에 배열의 크기 지정 및 값 초기화
int[][] arr = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
// or
int[][] arr = new int[][] {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

문자 배열

package test;

public class Test1StringArrayTest {
	public static void main(String[] args) {
		char[] alphabets = new char[26];
		char ch = 'A';
		
		for(int i = 0; i < alphabets.length; i++, ch++) {
			alphabets[i] = ch; // 아스키 값으로 각 요소에 저장
		}
		
		for(int j = 0; j < alphabets.length; j++) {
			System.out.println(alphabets[j]);
		}
	}
}

출력 결과 : A ~ Z 출력


객체 배열

동일한 기본 자료형 변수 여러 개를 배열로 사용할 수 있듯이 참조 자료형 변수도 여러 개를 배열로 사용할 수 있다.

package test;

public class Test2ObjectArrayTest1 {
	private String bookName;
	private String author;
	
	public Test2ObjectArrayTest1() {} // 기본 생성자
	
	public Test2ObjectArrayTest1(String bookName, String author) {
		this.bookName = bookName; // 책 이름을 매개변수로 받는 생성자
		this.author = author; // 저자 이름을 매개변수로 받는 생성자
	}
	
	public String getBookName() {
		return bookName; // getter
	}
	
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	
	public String getAuthor() {
		return author; // getter
	}
	
	public void setAuthor(String author) {
		this.author = author;
	}
	
	public void showBookInfo() {
		System.out.println(bookName + "," + author);
	} // 책 정보를 출력해 주는 메서드
}


package test;

public class Test2ObjectArrayTest2 {

	public static void main(String[] args) {
		Test2ObjectArrayTest1[] library = new Test2ObjectArrayTest1[5];
		
		for(int i = 0; i < library.length; i++) {
			System.out.println(library[i]);
		}
	}

}

결과 값 : null null null null null

인스턴스 주소 값을 담을 공간 5개가 생성되었다. null은 공간은 생성되었지만 비어있다는 의미

각 배열 요소에 인스턴스를 생성해 넣어보기

package test;

public class Test2ObjectArrayTest3 {

	public static void main(String[] args) {
		Test2ObjectArrayTest1[] library = new Test2ObjectArrayTest1[5];
		for(int i = 0; i < library.length; i++) {
			library[i] = new Test2ObjectArrayTest1("책 제목" + (i + 1), "책 저자" + (i + 1));
		}
		
		for(int i = 0; i < library.length; i++) {
			library[i].showBookInfo();
		}
		
		for(int i = 0; i < library.length; i++) {
			System.out.println(library[i]);
		}
	}

} // 클래스 명 짧게 할걸...

배열의 각 요소에 인스턴스를 직접 저장하고 인스턴스 주소값도 출력해보았다.


출력 값

책 제목1,책 저자1 책 제목2,책 저자2 책 제목3,책 저자3 책 제목4,책 저자4 책 제목5,책 저자5 test.Test2ObjectArrayTest1@38082d64 test.Test2ObjectArrayTest1@dfd3711 test.Test2ObjectArrayTest1@42d3bd8b test.Test2ObjectArrayTest1@26ba2a48 test.Test2ObjectArrayTest1@5f2050f6

배열 복사는 주말에 이어서 작성

참조 & 출저

ifuwanna-TiStory

profile
장래희망개발자

0개의 댓글