Arrays
배열
- 연속된 메모리 공간에 값을 나열시키고, 각 값에 Index 를 부여해 놓은 Data Structure 이다.
- 배열은 Homogeneous Data Structure (동질적 자료구조; 같은 타입의 값들만을 허용하는 자료구조) 이며,
배열의 길이는 늘리거나 줄일 수 없다.
Declaration Array (배열 선언)
type[] variable; // Type 1 (Conventional)
type variable[]; // Type 2
// Multidimensional Array
type[][] variable;
// Examples
int[] intArray;
double[] doubleArray;
String strArray[];
- 배열의 선언은 위와 같이 두가지 방법으로 가능하며, 관례적으로 첫 번째 방법을 주로 사용한다.
new Operator with Array (new 연산자)
type[] variable = new type[length];
type[][] variable = new type[length1D][length2D];
// Example
int[] intArray = new int[5];
int[][] intArray = new int[2][3];
int[][] intArray = newint[2][]; // 2차원 배열의 길이를 다양화
- new
연산자는 해당 길이의 배열 객체를 생성하고, 해당 객체의 메모리 주소를 반환한다.
Default Values of Array Element (기본값)
Element Type |
Default Value | |
Primitive Type |
byte[] | 0 |
char[] | '\u0000' | |
short[] | 0 | |
int[] | 0 | |
long[] | 0L | |
float[] | 0.0F | |
double[] | 0.0 | |
boolean[] | false | |
Reference Type |
Class[] | null |
Interface[] | null |
Array Members (배열의 속성 및 메서드)
- Array 는 Object Class 의 모든 Members 를 그대로 상속받는다.
(유일하게 clone() Method 만 재정의한다.)
* Obejct (Java SE 18 & JDK 18) (URL)
Array Property: length
public final length
- 배열의 원소 개수를 저장하고 있는 Property 이다.
- 양의 정수 혹은 0 의 범위를 가진다.
Array Method: clone()
public clone()
- Object Class의 clone() Method 를 Override 한 메서드이다.
- Checked Exceptions 을 Throws 하지 않는다.
- A clone of a multidimensional array is shallow,
which is to say that it creates only a single new array. Subarrays are shared.
An Array of Characters is Not a String (char 형 배열과 문자열의 차이)
- In the Java programming language, unlike C, an array of char is not a String,
and neither a String nor an array of char is terminated by '\u0000' (the NUL character).
- A String object is immutable, that is, its contents never change,
while an array of char has mutable elements.
- The method toCharArray in class String returns an array of characters containing the same character sequence
as a String.
- The class StringBuffer implements useful methods on mutable arrays of characters.
Libraries for Array (배열에 관련된 라이브러리)
Method: arraycopy()
java.lang.Object
java.lang.System
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
throws IndexOutOfBoundsException, ArrayStoreException, NullPointerException;
- 정해진 수 만큼의 배열 원소들을 복사한다.
- src
와 dest
가 동일한 Array Object 를 참조하는 경우,
src
의 원소가 임시 배열로 먼저 복사된 다음, dest
로 붙여넣어진다.
Parameter | Description |
Object src |
- Source Array |
int srcPos |
- Starting Position in the Source Array |
Object dest |
- Destination Array |
int destPos |
- Starting Position in the Destination Array |
int length |
- The Number of Array Elements to be copied |
Exception | Trigger Condition |
IndexOutOfBoundsException |
- srcPos 혹은 destPos 혹은 length 가 음수인 경우- srcPos+length 가 src.length 를 초과하는 경우- destPos+length 가 dest.length 를 초과하는 경우 |
ArrayStoreException |
- src 혹은 dest 이 배열 이외의 다른 객체를 참조하는 경우- src 배열과 dest 배열이 가진 원소들의 타입이 다른 경우(서로 다른 Primitive 타입이거나, 한쪽은 Primitive 타입, 다른 쪽은 Reference 타입인 경우) - src 배열의 원소가 dest 배열 원소의 타입으로 변환될 수 없는 경우(변환될 수 없는 원소 이전의 원소들은 정상적으로 복사된다.) |
NullPointerException |
- src 가 null 인 경우- dest 이 null 인 경우 |
Method: equals()
java.lang.Object
public boolean equals(Object obj);
- 두 객체가 참조하는 값을 비교한 결과를 true
혹은 false
로 반환한다.
- 어떤 경우에서든, x.equals(null)
은 false
를 반환한다.
- 일반적으로, 객체가 동일한 Hash Code를 갖게 하기 위해
equals()
메서드를 Override 하는 경우, hashCode()
메서드 또한 Override 되어야 한다.
Parameter | Description |
Object obj |
- Reference Object with which to Compare |
Iteration through Collections and arrays using for Loop (for 반복문을 통한 배열 순회)
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
- 위와 같이, for
문을 통해 Container 를 간편히 Iteration 할 수 있다.
- Oracle 에서는 일반적인for
문 형태를 통해 Iteration 하는 것 보다는
가능하면 위와 같은 형태로 Iteration 할 것을 권고하고 있다.
Reference: Oracle, Chapter 10. Arrays, URL, 2023년 3월 4일 검색
Reference: Oracle, System (Java SE 18 & JDK 18), URL, 2023년 3월 5일 검색
Reference: 신용권, 임경균; 이것이 자바다(개정판); 한빛미디어; 2022