배열(Array)

Yunsung·2024년 12월 28일
post-thumbnail

1. 배열(Array)

  • 정의: 같은 타입의 데이터를 하나의 묶음으로 관리하는 자료 구조.
  • 특징:
    - 고정된 크기를 가지며, 크기 변경이 불가능.
    - 데이터가 연속적으로 저장.
    - 배열의 인덱스는 0부터 시작.
    - 참조 타입으로 객체 생성이 필요.
    - 배열의 길이는 .length 속성으로 확인 가능.

배열 선언과 초기화

  1. 선언

    // int형식으로 10의 크기를 가지는 배열 선언
    int[] intAry = new int[10];
  2. 선언과 동시에 초기화

    String[] shapes = {"spade", "clover", "heart", "diamond"};


활용

  1. 데이터 할당 및 출력
  • 랜덤 값을 배열에 할당 후 출력

    public void AryRandom() {
    	int[] intAry = new int[10];
    	for (int i = 0; i < intAry.length; i++) {
       intAry[i] = (int) (Math.random() * 100) + 1;
       System.out.print(intAry[i] + "\t");
    	}
    }

    AryRandom() 출력 결과

    5, 17, 49, 37, 25, 23, 45, 12, 73, 39

  1. 랜덤 카드게임
  • 랜덤하게 카드 모양과 숫자 출력

    public String randomCardGame() {
    			
    	String result = null;
    	
    	System.out.println(">>> 랜덤 카드게임 <<<");
    			
    	// 배열 선언과 동시에 초기화
    	String[] shapes = {"spade", "clover", "heart", "diamond"};
    			
    	// A,J,Q,K가 들어가니까 String으로
    	String[] number = {"A", "2", "2", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "k"};   
    			
    	// random은 0.0 ~ 0.9 이기 때문에 4를 곱하면 3이 최대임.
    	int shapeIdx = (int)(Math.random() * shapes.length);
    	int numberIdx = (int)(Math.random() * number.length);
    			
    	result = "뽑은 카드는 " + shapes[shapeIdx] + " " + number[numberIdx] + " 입니다."; 
    			
    	return result;
    }
    

    randomCardGame() 출력 결과

    >>> 랜덤 카드게임 <<<
    뽑은 카드는 spade 5입니다.

  1. 로또 번호 생성
  • 중복 제거 및 정렬
    int lottoAry[] = new int[6];
    for (int i = 0; i < lottoAry.length; i++) {
       lottoAry[i] = (int) (Math.random() * 46) + 1;
       for (int j = 0; j < i; j++) {
           if (lottoAry[i] == lottoAry[j]) {
               i--; // 중복 시 다시 난수 생성
               break;
           }
       }
    }
    Arrays.sort(lottoAry); // 오름차순 정렬


2. 배열에 인스턴스 관리

2.1 생성자(Constructor)

생성자는 클래스의 멤버로서 객체가 생성될 때 호출되며, 주로 멤버 변수를 초기화하는 데 사용됩니다.

  • 특징
    - 메서드 이름이 클래스 이름과 동일해야 합니다.
    - 반환 타입이 없으며, 반환값을 명시할 수도 없습니다.
    - 기본 생성자와 스페셜 생성자로 나뉩니다.

  • 기본 생성자
    매개변수가 없는 생성자이며, 별도로 정의하지 않아도 컴파일러가 자동으로 생성합니다. 그러나 매개변수가 있는 생성자(스페셜 생성자)를 정의하면 기본 생성자는 자동으로 제공되지 않으므로 필요시 명시적으로 작성해야 합니다.

    public StudentVO() {
       // 기본 생성자: 아무 작업을 하지 않아도 명시적으로 작성하는 것이 좋습니다.
    }

2.2 스페셜 생성자(Special Constructor)

매개변수를 통해 값을 받아 멤버 변수를 초기화하는 생성자입니다. 객체 생성 시 다양한 초기화 값을 설정할 수 있도록 도와줍니다.

public StudentVO(int stuId) {
    this.stuId = stuId;  // 매개변수로 받은 값을 멤버 변수에 초기화
}

public StudentVO(int stuId, String name) {
    this.stuId = stuId;
    this.name = name;
}

2.3 생성자 오버로딩(Constructor Overloading)

생성자를 여러 개 정의할 수 있으며, 매개변수의 개수나 타입이 다르면 가능합니다. 이를 통해 객체 생성 시 다양한 초기화 방법을 제공할 수 있습니다.

// 매개변수 없는 생성자
public StudentVO() {
    this.stuId = 0;   // 기본 값으로 초기화
    this.name = "Unknown";
}

// 학번만 초기화
public StudentVO(int stuId) {
    this.stuId = stuId;
}

// 학번과 이름 초기화
public StudentVO(int stuId, String name) {
    this.stuId = stuId;
    this.name = name;
}


예제: 학생 객체 관리

1. StudentVO 클래스

학생 정보를 저장하는 VO(Value Object) 클래스. 생성자를 통해 다양한 초기화를 지원하며, getter와 setter 메서드로 데이터를 관리합니다.

public class StudentVO {
    private int stuId;
    private String name;

    // 기본 생성자
    public StudentVO() {}

    // 학번만 초기화하는 생성자
    public StudentVO(int stuId) {
        this.stuId = stuId;
    }

    // 학번과 이름을 초기화하는 생성자
    public StudentVO(int stuId, String name) {
        this.stuId = stuId;
        this.name = name;
    }

    // Getter & Setter
    public int getStuId() {
        return stuId;
    }

    public void setStuId(int stuId) {
        this.stuId = stuId;
    }

    public String getName() {
        return name;
    }

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

    // 학생 정보 출력 메서드
    public String stuInfo() {
        return "StudentVO [stuId=" + stuId + ", name=" + name + "]";
    }
}

2. RefAryApp 클래스

여러 학생 객체를 생성하여 배열로 관리하고, 배열에 저장된 객체 정보를 출력합니다.

public class RefAryApp {
    public static void main(String[] args) {
        // StudentVO 배열 생성
        StudentVO[] students = new StudentVO[3];

		// 배열에 객체 저장: 학번과 이름을 각각 지정
		students[0] = new StudentVO(1001, "Alice"); // 첫 번째 학생 객체 생성 및 배열 저장
		students[1] = new StudentVO(1002, "Bob");   // 두 번째 학생
		students[2] = new StudentVO(1003, "Charlie"); // 세 번째 학생

        // 배열 출력
        for (StudentVO student : students) {
            System.out.println(student.stuInfo());
        }
    }
}

3. 실행 결과

StudentVO [stuId=1001, name=Alice]
StudentVO [stuId=1002, name=Bob]
StudentVO [stuId=1003, name=Charlie]
profile
풀스택 개발자로서의 도전을 하는 중입니다. 많은 응원 부탁드립니다!!😁

0개의 댓글