자료구조&알고리즘

[JAVA자료구조] 1. List 구현

인생개발 이정환 2024. 8. 17. 14:37

List 인터페이스 직접 구현

import java.util.NoSuchElementException;

interface MyList<T> {
    void add(T item);        // 리스트 끝에 요소 추가
    T get(int index);        // 특정 인덱스의 요소 반환
    T remove(int index);     // 특정 인덱스의 요소 제거
    int size();              // 리스트의 크기 반환
    boolean isEmpty();       // 리스트가 비어 있는지 확인
}

class MyArrayList<T> implements MyList<T> {
    private Object[] array;  // 데이터를 저장할 배열
    private int size;        // 현재 리스트에 저장된 요소의 수

    // 생성자: 초기 크기 설정
    public MyArrayList(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("초기 용량은 0 이상이어야 합니다.");
        }
        this.array = new Object[initialCapacity];
        this.size = 0;
    }

    // 기본 생성자: 초기 크기를 10으로 설정
    public MyArrayList() {
        this(10);
    }

    @Override
    public void add(T item) {
        if (size == array.length) {
            resize(array.length * 2);  // 배열이 꽉 차면 크기를 2배로 늘림
        }
        array[size++] = item;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("잘못된 인덱스입니다.");
        }
        return (T) array[index];
    }

    @Override
    @SuppressWarnings("unchecked")
    public T remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("잘못된 인덱스입니다.");
        }
        T removedItem = (T) array[index];
        for (int i = index; i < size - 1; i++) {
            array[i] = array[i + 1];
        }
        array[--size] = null;
        return removedItem;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    // 내부적으로 배열 크기를 조정하는 메서드
    private void resize(int newCapacity) {
        Object[] newArray = new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newArray[i] = array[i];
        }
        array = newArray;
    }
}

public class Main {
    public static void main(String[] args) {
        MyList<Integer> list = new MyArrayList<>();

        // 리스트에 요소 추가
        list.add(10);
        list.add(20);
        list.add(30);

        // 요소 접근
        System.out.println("리스트 요소:");
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
        System.out.println();

        // 요소 삭제
        list.remove(1);  // 인덱스 1의 요소(20) 제거

        // 리스트의 크기와 요소 출력
        System.out.println("리스트 크기: " + list.size());
        System.out.println("리스트 요소:");
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
        System.out.println();
    }
}

주요 포인트

  1. MyList 인터페이스: List 인터페이스의 단순화된 버전입니다. add, get, remove, size, isEmpty 메서드를 정의했습니다.
  2. MyArrayList 클래스: MyList 인터페이스를 구현한 클래스입니다. 배열을 사용하여 요소를 저장하고, size 변수를 통해 리스트에 저장된 요소의 개수를 관리합니다.
  3. add 메서드: 리스트에 새로운 요소를 추가합니다. 배열이 꽉 차면 크기를 두 배로 늘립니다.
  4. get 메서드: 주어진 인덱스에 있는 요소를 반환합니다. 잘못된 인덱스 접근 시 IndexOutOfBoundsException을 발생시킵니다.
  5. remove 메서드: 특정 인덱스에 있는 요소를 제거하고, 배열의 나머지 요소를 앞으로 이동시킵니다.
  6. resize 메서드: 배열의 크기를 조정합니다. 이 메서드는 배열이 가득 찼을 때 또는 용량을 늘리거나 줄일 때 사용됩니다.