본문 바로가기

자료구조 구현하기

2. Class ArrayList


public class MyarrayList<E> implements MyList<E> {

    private static final int DEFALUT_CAPACITY = 10;
    private static final Object[] EMPTY_ARRAY = {};

    private int size = 0;

    Object[] array;

    public arrayList() {
        this.array = EMPTY_ARRAY;
        this.size = 0;
    }

    public arrayList(int capacity) {
        this.array = new Object[capacity];
        this.size = 0;
    }

    public void addLast(E value) {
        if (size == array.length) {
            resize();
        }

        array[size] = value;
        size++;
    }

    public void resize() {
        int array_capacity = array.length;

        if (Arrays.equals(array, EMPTY_ARRAY)) {
            array = new Object[DEFALUT_CAPACITY];
            return;
        }

        if (size == array_capacity) {
            int new_capacity = array_capacity * 2;

            array = Arrays.copyOf(array, new_capacity);
            return;
        }

        if (size < (array_capacity / 2)) {
            int new_capacity = array_capacity / 2;

            array = Arrays.copyOf(array, Math.max(new_capacity, DEFALUT_CAPACITY));
            return;
        }
    }

    public E get(int index) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException();
        }

        return (E) array[index];
    }

    public E remove(int index) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException();
        }

        E element = (E) array[index];
        array[index] = null;

        for (int i = 0; i < size - 1; i++) {
            array[i] = array[i+1];
            array[i+1] = null;
        }

        size--;
        resize();
        return element;
    }
}

'자료구조 구현하기' 카테고리의 다른 글

Map  (0) 2022.08.27
1. interface List  (0) 2022.06.13
1. interface List  (0) 2022.06.13
0. interface Collection  (0) 2022.06.08
0. 계층도  (0) 2022.06.08