ArraySet.java 1.98 KB
import java.util.Iterator;

public class ArraySet<E> implements ISet<E> {
    private static final int DEFAULT_CAPACITY = 10;
    private static final double GROW_FACTOR = 2.0;
    private E[] data;
    private int size;

    public ArraySet() {
        this.data = (E[])new Object[DEFAULT_CAPACITY];
    }

    private void ensureCapacity(int size) {
        if (this.capacity() < size) {
            E[] newData = (E[])new Object[(int)(this.capacity()*GROW_FACTOR)];
            for (int i = 0; i < this.size; i++) {
                newData[i] = this.data[i];
            }
            this.data = newData;
         }
    }

    private int capacity() {
        return this.data.length;
    }

    public int size() {
        return this.size;
    }

    @Override
    public void add(E elem) {
        if (!this.contains(elem)) {
            this.ensureCapacity(this.size + 1);
            this.data[this.size] = elem;
            this.size++;
        }

    }

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

    @Override
    public Iterator<E> iterator() {
        return new ArraySetIterator();
    }

    /*
    [1, 2, 3]

    idx=0, next() => 1
    idx=1
    hasNext() 1 < 3 true
    idx=1, next() => 2
    hasNext() 2 < 3 true

     */

    private class ArraySetIterator implements Iterator<E> {
        private int idx;
        public ArraySetIterator() {
            this.idx = 0;
        }

        @Override
        public boolean hasNext() {
            return this.idx < size();
        }

        @Override
        public E next() {
            E toReturn = data[this.idx];
            this.idx++;
            return toReturn;
        }
    }

    @Override
    public String toString() {
        if (this.isEmpty()) {
            return "[]";
        }

        String result = "[";
        for (int i = 0; i < this.size; i++) {
            result += this.data[i] + ", ";
        }

        result = result.substring(0, result.length() - 2);
        return result + "]";
    }
}