ArrayList 구현(Java)

브로디·2024년 2월 18일
0

List인터페이스를 구현하기엔 강제되는 메서드가 많아 핵심메서드만 뽑아서 클래스를 만들었다.
Vector는 ArrayList의 레거시 클래스로 기본 아이디어는 비슷하다.

핵심은 2가지다.

1) Array는 물리적으로 일련의 메모리주소를 갖기 때문에 접근이 빠르다.
2) 특정 인덱스의 객체를 지울 떄 다른 데이터의 위치를 이동시켜 줘야 하기 때문에 데이터가 많으면 오래 걸린다.

public class MyVector {
    Object[] data = null; // 객체를 담기위한 객체 배열.
    int capacity = 0; // 용량
    int size = 0; // 크기

    public MyVector(int capacity) {
        if (capacity < 0) {
            throw new IllegalArgumentException("유효하지 않은 값입니다:" + capacity);
        }

        this.capacity = capacity;
        data = new Object[capacity];
    }

    public MyVector() {
        this(10);
    }

    public void ensureCapacity(int minCapacity) {
        if (minCapacity - this.capacity > 0) {
            setCapacity(minCapacity);
        }
    }

    public boolean add(Object obj) {
        ensureCapacity(size+1);
        data[size++] = obj;
        return true;
    }

    public Object get(int index) {
        if(index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("범위를 벗어났습니다.");
        }
        return data[index];
    }

    public Object remove(int index) {
        if(index < 0 || index >= this.size) {
            throw new IndexOutOfBoundsException("범위를 넘어섰습니다.");
        }

        Object oldObj = data[index];
        if(index != size-1) {
            System.arraycopy(data, index+1, data, index, size-index-1);
        }
        data[size-1] = null;
        this.size--;

        return oldObj;
    }

    // 객체를 찾고 그 인덱스에 해당하는 remove를 호출
    public boolean remove(Object obj) {
        for (int i=0; i<size; i++) {
            if (data[i].equals(obj)) {
                remove(i);
                return true;
            }
        }
        return false;
    }

    public void trimToSize() {
        setCapacity(size);
    }

    private void setCapacity(int capacity) {
        Object[] tmp = new Object[capacity];
        System.arraycopy(tmp, 0, data, 0, size);
        data = tmp;
        this.capacity = capacity;
    }

    public void clear() {
        for (int i = 0; i<size; i++) {
            data[i] = null;
        }
        size = 0;
    }

    public Object[] toArray() {
        Object[] result = new Object[size];
        System.arraycopy(data, 0, result, 0, size);

        return result;
    }

    public boolean isEmpty() { return size==0; }
    public int capacity() { return capacity; }
    public int size() { return size; }
}
profile
햅삐햅삐 데이

0개의 댓글