Implementierung einer GenericArrayList in Java

Einleitung

Eine einfache Implementation einer eigenen GenericArrayList in Java bietet der folgende Code.

package arraylist;

interface GenericList<E> {
    E get(int idx);              // retrieve element at index
    void set(E el, int idx);     // overwrite element at index
    int size();                  // get number of elements
    void add(E el);              // append to end
    void remove(int idx);        // remove at index
    void insert(E el, int idx);  // insert at index
}

public class GenericArrayList<E> implements GenericList<E>
{
    E[] content;
    int size;
    public GenericArrayList(int capacity)
    {
        content = (E[]) new Object[capacity];
        size = 0;
    }

    public int size()
    {
        return size;
    }

    public void add(E element)
    {
        if (size == content.length)
        {
            increaseCapacity();
        }
        content[size++] = element;
    }

    private void increaseCapacity()
    {
        E[] tmp = (E[]) new Object[size * 2 + 1];
        for(int i = 0; i < content.length; i++)
        {
            tmp[i] = content[i];
        }
        content = tmp;
    }

    public void remove(int idx)
    {
        size--;
        for(int i = idx; i < size; i++)
        {
            content[i] = content[i + 1];
        }
    }

    public void insert(E d, int idx)
    {
        if (size == content.length)
        {
            increaseCapacity();
        }

        for(int i = size - 1; i >= idx; i--)
        {
            content[i + 1] = content[i];
        }
        content[idx] = d;
        size++;
    }

    public void set(E el, int idx)
    {
        content[idx] = el;
    }

    public E get(int idx)
    {
        return content[idx];
    }
}

Weitere Beiträge aus dieser Serie

Schreibe einen Kommentar

Notify me of followup comments via e-mail. You can also subscribe without commenting.