Array와 ArrayList의 공통점
1.
index로 값을 참조한다
2.
중복 요소를 저장할 수 있다
Array와 ArrayList의 차이점
1. 사이즈의 가변성
•
Array는 선언 시 크기를 지정해주어야 한다
•
한 번 선언된 Array의 크기는 변경할 수 없다
int[] arr = new int[5];
int[] arr2 = new int[]; // 컴파일 에러
Java
복사
•
ArrayList는 선언 시 크기를 정해주지 않아도 된다.
•
크기를 정하지 않을 경우, 기본적으로 10의 크기를 갖게 된다.
ArrayList<Integer> arrayList = new ArrayList<>();
Java
복사
•
데이터가 더 추가되어 크기가 늘어나는 경우
→ 우측 시프트 연산을 통해 크기를 현재 크기 + (현재 크기 * 0.5) 로 증가시킨다.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 현재 크기 + (현재 크기 * 0.5)
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity <= 0) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
return Math.max(DEFAULT_CAPACITY, minCapacity);
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;
}
return (newCapacity - MAX_ARRAY_SIZE <= 0)
? newCapacity
: hugeCapacity(minCapacity);
}
Java
복사
2. 내부 데이터 타입 종류
•
Array는 Primitive type과 Object를 담을 수 있다
int[] arr = new int[5];
Integer[] arr2 = new Integer[5];
Class[] arr3 = new Class[5];
Java
복사
•
ArrayList는 Object만 담을 수 있다.
→ Primitive type을 담을 수 없다.
•
Primitive type을 담을 경우, JVM이 내부적으로 Autoboxing을 통해 Object로 변환한다
ArrayList<Integer> arrayList = new ArrayList<>();
ArrayList<int> arrayList2 = new ArrayList<>(); // 컴파일 에러
arrayList.add(10);
arrayList.add(new Integer(10)); // 위 코드는 내부적으로 형 변환 되어 처리된다
Java
복사
3. 데이터의 삽입
•
Array는 = 연산자를 이용해 요소를 추가한다
int[] arr = new int[5];
arr[0] = 5;
Java
복사
•
ArrayList는 .add() 메서드를 이용해 요소를 추가한다
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(10);
Java
복사
4. 다차원
•
Array는 다차원이 가능하다
int[][] arr = new int[5][10];
Java
복사
•
ArrayList는 단일 차원만 가능하다
Array | ArrayList | |
식별자 | index | index |
사이즈 | 선언 시 초기화
크기 변경 불가 | 선언 시 초기화 필요 없음
크기가 가변적 |
데이터 타입 | Primitive type
Object | Object |
데이터의 삽입 | = 연산자 | .add() 메서드 |
다차원 | 다차원 가능 | 단일차원 |
한 줄 정리
Array와 ArrayList 둘 다 index로 식별자를 사용하며 중복되는 요소를 저장할 수 있다.
Array는 선언 시 크기를 지정해야 하고, 지정 후 크기를 변경할 수 없다. ArrayList는 선언 시 크기를 지정할 필요가 없고, 크기가 가변적이다.
Array는 primitive type과 object를 담을 수 있지만 ArrayList는 Object만 담을 수 있다
Array는 요소를 담을 때 대입 연산자를 이용하고, ArrayList는 .add() 메서드를 이용한다
Array는 다차원이 가능하고 ArrayList는 다차원이 불가능하다.