Details of the data structure were covered in class. Basically, we maintain the
invariant that check[check_index[key]] == key when the information in the
dictionary for key is valid, and one of the indices will be out of range or have an
incorrect value otherwise.
// CS410 Fall 1999, Homework 1 Question 10
class InvalidKey extends Exception {}
class DictionaryAbsent extends Exception {}
class Dictionary {
// Strictly speaking, in Java all data is initialised.
// But assume that the arrays check, check_index, and data are not
// initialised by the new expressions below.
// The indices check[0] ... check[check_size-1] of check_index and data
// are initialised, furthermore if check[i]=j (where 0 <= i < check_size) then
// check_index[j]=i.
// Therefore we can check if a given key is present by checking:
// 0 <= check_index[key] < check_size and check[check_index[key]]==key
private int check_size;
private int check[];
private int check_index[];
private Object data[];
public Dictionary(int max_key) {
check_size = 0;
check = new int[max_key];
check_index = new int[max_key];
data = new Object[max_key];
}
public boolean valid(int key) throws InvalidKey {
// Check key is in range
if (!(0 <= key && key < check.length)) throw new InvalidKey();
// Check if present
int chk_ind = check_index[key];
return 0 <= chk_ind && chk_ind < check_size && check[chk_ind]==key;
}
public void insert(int key, Object value) throws InvalidKey {
if (!valid(key)) {
// Not present; initialise
int chk_ind = check_size++;
check[chk_ind] = key;
check_index[key] = chk_ind;
}
// Set data
data[key] = value;
}
public void delete(int key) throws InvalidKey {
if (valid(key)) {
// Present; delete it
check_size--;
int chk_ind = check_index[key];
if (chk_ind != check_size) {
// Swap check entry for key with the top of stack
check[chk_ind] = check[check_size];
check_index[check[check_size]] = chk_ind;
}
} // Otherwise do nothing
}
public Object lookup(int key) throws InvalidKey, DictionaryAbsent {
if (valid(key))
return data[key]; // Present; return data
else
throw new DictionaryAbsent(); // Absent; throw exception
}
}