import java.util.Arrays;

public class RArrayList implements RList {
    private int data[];
    private int size;

    public RArrayList() {
        data = new int[3];
        size = 0;
    }

    public String toString() {
        //return Arrays.toString(data);
        String answer = "[ ";
        for (int x = 0; x < size; x++) {
            answer += data[x];
            answer += " ";
        }
        return answer + "]";
    }

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

    @Override
    public int get(int pos) {
        if (pos >= 0 && pos < size) {
            return data[pos];
        } else {
            throw new ArrayIndexOutOfBoundsException("index " + pos + " is out of bounds.");
        }
    }

    @Override
    public void set(int pos, int value) {
        data[pos] = value;
    }

    @Override
    public void append(int value) {
        if (size == data.length) { // no room, so expand
            expand();
        }
        // now we are guaranteed that there is room in the array

        // put new item at end of array and increase size
        data[size] = value;
        size++;

    }

    @Override
    public void prepend(int value) {
        if (size == data.length) { // no room, so expand
            expand();
        }
        // now we are guaranteed that there is room in the array

        // shift all elements one spot to the right
        for (int x = data.length-2; x >= 0; x--) {
            data[x+1] = data[x];
        }

        // put new element at position 0 and increase size
        data[0] = value;
        size++;
    }

    private void expand() { // function to add three new spots to the end of the array
        int[] newdata = new int[data.length + 3];   // reserve space
        for (int x = 0; x < size; x++) {            // copy elements
            newdata[x] = data[x];
        }
        data = newdata;
    }

}
