[자바의정석]Chapter 05. 배열

seungwon·2023년 1월 4일
0

자바의 정석

목록 보기
5/14

1. 배열(array)

1.1 배열이란?

배열 : 같은 타입의 여러 변수를 하나의 묶음으로 다루는 것

1.2~1.4 배열의 선언, 생성, 초기화

선언방법선언예
타입[] 변수이름;int[] score; \\ String[] name;
타입 변수이름[];int score[]; \\ String name[]

👽 배열의 생성

타입[] 변수명 = new 타입[길이]
ex) int[] score = new int[5];

생성 과정
1. int[] score;
int형 배열 참조변수 선언
2. score = new int [5];

  • 연산자 ‘new’에 의해서 메모리의 빈 공간에 5개의 int형 데이터를 저장할 수 있는 공간
    이 마련됨
  • 각 배열 요소는 자동적으로 int의 기본값 0으로 초기화 됨
  • 대입연산자 '='에 의해 배열의 주소가 int형 배열 참조변수에 저장된다

👽 배열의 생성과 동시에 초기화 하는 방법

int[] score = new int[]{10,20,30,40}
int[] score = {10,20,30,40} : new를 생략할 수도 있음

생성과 초기화를 따로 하는 경우 new 생략 불가

int[] score;
score = {10,20,30,40}; // 🚨에러

메서드를 호출하는 경우에도 new 생략 불가
int result = add(new int[]{10,20,30,40})
int result = add({10,20,30,40}) : 🚨에러

👽 배열의 길이

배열의 길이 >=0>= 0 (0인 배열도 생성 가능)

배열이름.length

👽 배열 출력

  • for문 활용

  • toString()활용

    import.java.util.*;
    
    class example{
       public static void main(String[] args){
           int[] iArr = {10,20,30,40};
           System.out.println(Arrays.toString(iArr));
       }
    }

    💻 [10, 20, 30, 40]

  • 참조 변수를 출력하면 배열의 주소가 출력됨
    *char 배열은 print()/println()으로 출력시 각 요소가 구분자 없이 그대로 출력됨

    import.java.util.*;
    
    class example{
       public static void main(String[] args){
           char[] iArr = {'a','b','c','d'};
           System.out.print(iArr);
       }
    }

    💻 abcd

1.5 배열의 복사

  1. for문 활용
  2. System.arraycopy()
    ex. System.arraycopy(from, idx, to, idx, len)
    \quad = from[idx] 부터 len만큼 to[idx]으로 복사
    *복사하려는 내용 내용보다 여유 공간이 적으면 에러 발생(ArraylndexOutOffioundsException)

2. String 배열

String은 실제로는 클래스 -> 원래는 new 연산자를 통해 객체를 생성해야 함
ex)

String[] name = new String[3]
name[0] = new String("Kim");
name[1] = new String("Park");
...

String 클래스만 예외적으로 허용 -> 아래와 같이 가능

String[] name = new String[3]
name[0] = "Kim";
name[1] = "Park";
...

String 클래스의 주요 메서드

메서드명설명
char charAt(int index)문자열에서 해당 위치 (index)에 있는 문자를 반환한다.
int length()문자열의 길이를 반환한다.
String substring (int from, int to)문자열에서 해당 범위 (from~to)에 있는 문자열을 반환한다.(to는 범위에 포함되지 않음)
boolean equals(Object obj)문자열의 내용이 obj와 같은지 확인한다. 같으면 결과는 true, 다르면 false가 된다.
char[ ] toCharArray()문자열을 문자배열(char[])로 변환해서 반환한다.

3. 다차원 배열

선언 방법

선언 방법선언 예
타입[][] 변수이름;int[][] score;
타입 변수이름[][];int score[][];
타입[] 변수이름[];int[] score[];

3.3 가변 배열

*가변배열도 생성과 동시에 초기화 가능
ex)

int[][] score={
				{100,100,100,100},
                {90,80,70}.
                {0,100}
              };
                

3개의 댓글

comment-user-thumbnail
2023년 2월 10일

your code is so strong doodle jump

답글 달기
comment-user-thumbnail
2023년 5월 19일

best technical structure based on the concept of creating a technical disability correction on time krunker

답글 달기
comment-user-thumbnail
2023년 12월 8일

You should still learn more about run 3 games because they're so popular right now, even though I'm sure you'll need what you learned in that post.

답글 달기