지식조각모음
Chapter 5. 배열 본문
참고: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
01. 배열이란?
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
- 같은 타입의 여러 변수를 하나의 묶음으로 다루는 것.
- 배열의 길이는 배열이 생성될 때 정해지며, 생성 이후에는 그 길이가 고정된다.
02. 배열의 선언과 생성
// 배열 선언(배열을 다루기 위한 참조변수 선언)
// 타입[] 변수이름;
int[] scores;
// 배열 생성(실제 저장공간을 생성)
// 변수이름 = new 타입[길이];
scores = new int[5];
- 타입은 Object이기만 하면 어떤 것이든 사용 가능
03. 배열의 인덱스
- 생성된 배열의 각 저장공간을 '배열의 요소(element)'라고 한다.
- 이 인덱스로 배열의 요소에 접근한다.
- 인덱스가 0부터 시작하는 이유
- 인덱스는 배열의 요소의 위치를 말한다.
- score[0]은 배열이 저장된 위치에서 0번째란 뜻이다
- 'score의 주소값 = score[0]의 주소값'이고, 인덱스가 1 증가하는 것은 배열의 타입의 저장공간만큼 움직인단 뜻
04. 배열의 길이
// 배열이름.lenght
score.lenght
'배열이름.lenght'은 상수이다. JVM이 모든 배열의 길이를 별도로 관리하며, '배열이름.lenght'를 통해서 배열의 길이에 대한 정보를 얻을 수 있다.
[궁금점] 배열은 Class가 아닌데 length는 어디에 정의되어 있을까??
Arrays are special objects in java, they have a simple attribute named length which is final. There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
- length는 단순 final 변수이다.
- 일반 필드처럼 엑세스 되지 않는다. 실제로 length에 접근하려고 해도 아무런 이동도 없다.
length는 실제 사용 중인 배열의 크기를 가져오는 것이 아니라, 사용 가능한 길이(할당된 크기)를 가져오는 것이다.

05. 배열의 초기화
배열은 생성과 동시에 자동적으로 기본값으로 초기화 된다
06. 배열의 출력
int[] iArr = {10, 20, 30, 40, 50};
System.out.print(iArr); // 타입@주소 출력
System.out.print(Arrays.toString(iArr)); // 10, 20, 30, 40, 50
// [예외] char 배열
char[] chArr = {'a', 'b', 'c', 'd', 'e'};
System.out.println(chArr); // abcde
Where is array's length property defined?
We can determine the length of an ArrayList<E> using its public method size(), like ArrayList<Integer> arr = new ArrayList(10); int size = arr.size(); Similarly we can determine the l...
stackoverflow.com
Chapter 10. Arrays
int[] ai; // array of int short[][] as; // array of array of short short s, // scalar short aas[][]; // array of array of short Object[] ao, // array of Object otherAo; // array of Object Collection [] ca; // array of Collection of unknown type The declara
docs.oracle.com
'책 > 자바의 정석' 카테고리의 다른 글
| Comparator와 Comparable (1) | 2022.03.10 |
|---|---|
| 11. 컬렉션 프레임웍 (0) | 2022.03.06 |
| 10. 날짜와 시간 & 형식화 (1) | 2022.03.05 |
| 9. java.lang 패키지와 유용한 클래스 (0) | 2022.03.03 |
| 8. 예외처리 (4) | 2022.03.03 |