HashTable.java

package ch.hslu.exercises.sw04.ex1;

import java.util.Arrays;

public final class HashTable implements Table<Integer> {

    private final Integer[] data;
    private int size = 0;

    public HashTable(final int size) {
        data = new Integer[size];

    }

    @Override
    public boolean add(final Integer element) {
        if (element != null) {
            data[getIndexFromHashCode(element.hashCode())] = element;
            size++;
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean remove(final Integer element) {
        if (element != null) {
            Integer possibleElement = data[getIndexFromHashCode(element.hashCode())];
            if (element.equals(possibleElement)) {
                data[getIndexFromHashCode(element.hashCode())] = null;
                size--;
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean contains(final Integer element) {
        if (element != null) {
            Integer possibleElement = data[getIndexFromHashCode(element.hashCode())];
            return element.equals(possibleElement);
        }
        return false;
    }

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

    private int getIndexFromHashCode(final int hashCode) {
        return hashCode % data.length;
    }

    @Override
    public String toString() {
        return "HashTable{"
                + "data=" + Arrays.toString(data)
                + ", size=" + size
                + '}';
    }
}