package table;

public class Table {

	private class Entry {

		String key, value;
		Entry next;

		Entry(String key, String value, Entry next) {
			this.key = key;
			this.value = value;
			this.next = next;
		}

		public String toString() {
			return "(\"" + key + "\" => \"" + value + "\") " + next;
		}

	}

	private Entry[] table;

	public Table(int size) {
		table = new Entry[size];
	}

	public String toString() {
		String s = "";
		for (int i = 0; i < table.length; i++)
			s += "[" + i + "] = " + table[i] + "\n";
		return s;
	}

	public void store(String key, String value) throws DuplicateException {
		try {
			retrieve(key);
			throw new DuplicateException(key);
		} catch (MissingException e) {
			int h = key.hashCode() % table.length;
			table[h] = new Entry(key, value, table[h]);
		}
	}

	public String retrieve(String key) throws MissingException {
		Entry e = table[key.hashCode() % table.length];
		while (e != null) {
			if (key.equals(e.key))
				return e.value;
			e = e.next;
		}
		throw new MissingException(key);
	}
}
