이 글을 시작으로 알고리즘에서 자주 사용되는 자료구조의 주요 메소드를 정리하는 포스트를 작성해보겠습니다. 이번 포스트에서는 ArrayList 자료구조에 대해 정리해보겠습니다.
ArrayList
- ArrayList는 Java 컬렉션 프레임워크(Collection Framework) 중 하나로, 배열 기반으로 구현된 동적 크기 배열(Dynamic Array) 입니다.
- 배열과 비슷하지만, 크기를 자동으로 조정해주기 때문에 요소를 추가하거나 삭제할 때 편리합니다.
주요 특징
자료구조 | 내부적으로 배열(Array) 사용 |
크기 조정 | 배열이 꽉 차면, 자동으로 1.5배 또는 2배 크기로 확장 |
접근 속도 | 인덱스로 접근 시 빠름 (O(1)) |
삽입/삭제 속도 | 중간 삽입/삭제는 느림 (O(N)) (이동 필요) |
중복 허용 | O (같은 값을 여러 번 저장 가능) |
null 허용 | O (null 값 저장 가능) |
대표 메서드
package structure.arraylist;
import java.util.List;
public class ArrayListClass {
private final List<Integer> arrayList;
public ArrayListClass(List<Integer> arrayList) {
this.arrayList = arrayList;
}
// 리스트의 끝에 지정된 값을 추가합니다.
// 시간 복잡도: O(1) (배열 크기 조정이 필요한 경우 O(n))
// 예외 발생: NullPointerException - arrayList가 null인 경우
public List<Integer> add(int value) {
this.arrayList.add(value);
return this.arrayList;
}
// 지정된 인덱스의 요소를 제거합니다.
// 시간 복잡도: O(n) (제거 후 요소를 이동해야 하기 때문)
// 예외 발생: IndexOutOfBoundsException - 인덱스가 리스트 범위를 벗어난 경우
// 예외 발생: NullPointerException - arrayList가 null인 경우
public List<Integer> removeOfIndex(int index) {
this.arrayList.remove(index);
return this.arrayList;
}
// 리스트에서 지정된 값의 첫 번째 발생을 제거합니다.
// 시간 복잡도: O(n) (값을 찾고 요소를 이동해야 하기 때문)
// 예외 발생: NullPointerException - arrayList가 null인 경우
public List<Integer> removeOfValue(int value) {
this.arrayList.remove(Integer.valueOf(value));
return this.arrayList;
}
// 지정된 인덱스의 요소를 반환합니다.
// 시간 복잡도: O(1)
// 예외 발생: IndexOutOfBoundsException - 인덱스가 리스트 범위를 벗어난 경우
// 예외 발생: NullPointerException - arrayList가 null인 경우
public int get(int index) {
return this.arrayList.get(index);
}
// 지정된 인덱스의 요소를 주어진 값으로 대체합니다.
// 시간 복잡도: O(1)
// 예외 발생: IndexOutOfBoundsException - 인덱스가 리스트 범위를 벗어난 경우
// 예외 발생: NullPointerException - arrayList가 null인 경우
public List<Integer> set(int index, int value) {
this.arrayList.set(index, value);
return this.arrayList;
}
// 지정된 인덱스에 값을 삽입합니다.
// 시간 복잡도: O(n) (삽입 후 요소를 이동해야 하기 때문)
// 예외 발생: IndexOutOfBoundsException - 인덱스가 리스트 범위를 벗어난 경우
// 예외 발생: NullPointerException - arrayList가 null인 경우
public List<Integer> add(int index, int value) {
this.arrayList.add(index, value);
return this.arrayList;
}
// 리스트에 지정된 값이 포함되어 있는지 확인합니다.
// 시간 복잡도: O(n) (리스트를 순차적으로 검색)
// 예외 발생: NullPointerException - arrayList가 null인 경우
public boolean contains(int value) {
return this.arrayList.contains(value);
}
// 리스트에서 지정된 값의 첫 번째 인덱스를 반환합니다.
// 시간 복잡도: O(n) (리스트를 순차적으로 검색)
// 예외 발생: NullPointerException - arrayList가 null인 경우
public int indexOf(int index) {
return this.arrayList.indexOf(index);
}
// 리스트의 모든 요소를 제거합니다.
// 시간 복잡도: O(1) (참조를 제거하는 작업)
// 예외 발생: NullPointerException - arrayList가 null인 경우
public void clear() {
this.arrayList.clear();
}
// 리스트의 요소 개수를 반환합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - arrayList가 null인 경우
public int size() {
return this.arrayList.size();
}
}
'자료구조' 카테고리의 다른 글
LinkedList - Java (5) | 2025.04.27 |
---|---|
자료구조 정의 (0) | 2025.04.27 |