JAVA SPRING/java

JAVA_003) 배열

오동순이 2023. 1. 26. 18:00

배열 Array


배열로  만들어진 각 데이터들은 연속적인 메모리 공간 만들어짐
배열변수에는 배열리 생성된 곳의 메모리값을 저장하는 참조형 변수.

타입[] 배열이름 = new 타입[생성개수]
int[] array = new int[5]

일반변수는 연속적인 위치에 생성되지 않음.
(생성의  횟수와 위치가 같지 않을 수 있음.)

참조형 변수는 생성되면 null(비어있음)이 생성

0은 0이라는 값이 저장되어있음

public class ArrayEx01 {
    public static void main(String[] args) {
        int[] arr1 = {10, 20, 30}; // 요즘 방식 생성하는 동시에 값입력

        int[] arr2= new int[3]; // 생성후 값 입력
        arr2[0] = 10;
        arr2[1] = 20;
        arr2[2] = 30;

        // arr2 = {10, 20, 30}; 안됨

        arr2 = new int[]{10, 20, 30}; 
        int arr3[] = new int[3]; // Old st 옛날 방식

        int size = 10;
        int[] arr4 = new int[size]; // 배열의 크기는 변수로 설정 가능(반드시, 정수 만 입력가능)

    }
}

인덱스번호의 시작은? 컴퓨터 숫자의 시작은 0 ! 배열의 시작도 0 !

int i1 =0, i2 = 0, i3 = 0; // 연속적으로 생성X 무작위 생성O
int[] arr = new int[3]; // 생성(선언) //연속적으로 담는 공간 생성후 그 주소를 찾아감

 

 

배열 요소의 초기화 & 배열 요소의 조회(for)

public class ArrayEx {
    public static void main(String[] args) {
        int[] arr = new int[5];
        // 배열 요소의 초기화
        for(int i=0; i<5; i++){
            arr[i] = (i+1)*10;
        }
        // 배열 요소의 조회

        for(int i=0; i<5; i++){
            System.out.println(arr[i]);  //index기반
        }
            //arr 배열의 첫 번재 부터 차례대로 접근해서 조회한다
            //조회된 값은 i 에 복사된다.

            //조회만 가능 수정 불가!

        for(int i : arr){
            System.out.println(i);       //무조건 처음부터 끝까지 순차조회
        }

    }
}

 

 

배열 생성, 배열의 인덱스 번호는 어떻게 되나요?

public class ArrayEx02 {
    public static void main(String[] args) {
        int[] arr1 = new int[3];
        
        int[] arr2 = {5, 10, 15}; // 배열 생성 {} 중괄호! // 배열의 길이 변경 불가
        // arr2 = {10, 20, 30, 40, 50} 은 불가능! 이미 생성되어 있음
        
        arr2[0] = 55;  // 내용은 변경가능

        double[] arr3 = new double[3];
        arr3[0] = 70; //자동형변환 70.0
        
        boolean[] arr4 = new boolean[3];
        arr4[0] = true; // or false
        
        // char[] arr5 = new char[3];
        // arr5[0] = 'a';

        // 문자열의 끝에는 \0 가 항상 있음
        //번호.         1   2   3   4   5   6   7   8   9   10  11  12
        char[] arr5 = {'H','e','l','l','o',' ','W','o','r','l','d','!','\0'};
        System.out.println(arr5);
        System.out.println(arr4);


        String str = "Hello World!"; // String 은 char의 배열이다!
        System.out.println(str.charAt(0));
        System.out.println(str.toCharArray()[0]);
        System.out.println(str.substring(0, 5));
        System.out.println(str.substring(6, 12));

        String[] strArr =  new String[5];
        String[] strArr2 = {"asd", "fgh", "hjk"};

        //타입에따라 배열을 만들수있다. (변수를 생성할수있는 타입일 경우!) ex목록을 만드는 것


    }
}

 

배열은 유동적이지 않아요

 

배열으로 이름과 점수 입력과 조회

import java.util.Scanner;

public class ArrayEx03 {
    public static void main(String[] args) {
        // 점수를 입력하고 조회
        int[] score = {95, 85, 80, 70, 92};
        String[] name = {"송종하", "정시안", "손경은", "송효빈", "안해일"};
        
        Scanner s = new Scanner(System.in);

        while(true){
            System.out.print("조회 할 학생의 번호 (0-4) -1 to quit :");
            int n = s.nextInt();
            if(n == -1){
                break;
            }
            else if(n >= 0 && n <= 4){
                System.out.println("이름 : "+name[n]);
                System.out.println("점수 : "+score[n]+"점");
            }
            else{
                System.out.println("잘못된 번호입니다 [번호범위 : 0 - 4]");
            }
        }

        System.out.println("종료합니다.");
        s.close();


    }
}

 

 

while문과 switch문을 이용해서 배열에 점수추가와 점수조회방법 콘솔

import java.util.Scanner;

public class ArrayEx03 {
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        System.out.print("생성할 데이터 수 : ");
        int len = s.nextInt();
        int[] score = new int[len];
        String[] name = new String[len];

        int next_index = 0; // 점수추가

        while(true){
            System.out.print("1. 점수추가, 2. 점수조회, 0:종료 :");
            int sel = s.nextInt();
            s.nextLine(); // 엔터키 입력을 비우기 위해 추가함
            
            switch(sel){
                case 1:
                    if(next_index > len-1){
                        System.out.println("더 이상 입력 할 수 없습니다.");
                    }
                    else{
                        System.out.print("이름 : ");
                        String stu_name = s.nextLine();
                        System.out.print("점수 : ");
                        int stu_score = s.nextInt();
                        s.nextLine(); // 엔터키 입력을 비우기 위해 추가함
                        name[next_index] = stu_name;
                        score[next_index] = stu_score;
                        System.out.println("점수가 저장되었습니다.");
                        next_index++; // 인덱스 추가 
                    }
                    break;
                case 2:
                    System.out.print("조회 할 학생의 번호 (0-"+(len -1)+") :");
                    int n = s.nextInt();
                    
                    if(n >= 0 && n < len){
                        System.out.println("이름 : "+name[n]);
                        System.out.println("점수 : "+score[n]+"점");
                    }
                    else{
                        System.out.println("잘못된 번호입니다 [번호범위 : 0 - 4]");
                    }
                    break;
                case 0:
                    System.out.println("종료합니다.");
                    s.close();
                    return;
                default:
                    System.out.println("잘못된 메뉴 번호 입니다.");
            }
        }


    }
}

 


다차원 배열이란 ? 

참고블로그 : https://simplex3510.tistory.com/214

1차원 배열은 1열로된 저장공간(세로)
2차원 배열은 행렬로 된 저장공간(matrix)
[1][2][3]
[1][2][3]
[1][2][3]

[1] 세로-> 1차원
[1]
[1]
  
[1][2][3] <- 행이 추가
   ^^^


Tip

배열의 가벼운 복사 : 셸로우 카피 shallow copy
배열의 완전한 복사 : 딥 카피 deep copy