73 lines
1.9 KiB
Java
73 lines
1.9 KiB
Java
package Models.Program;
|
|
|
|
import Exceptions.BaseException;
|
|
|
|
import java.util.Collection;
|
|
import java.util.Hashtable;
|
|
|
|
public class GenericDictionary<K, V> implements IDictionary<K, V> {
|
|
private Hashtable<K, V> dictionary;
|
|
|
|
public GenericDictionary() {
|
|
dictionary = new Hashtable<K, V>();
|
|
}
|
|
|
|
public void add(K key, V value) throws BaseException {
|
|
if (dictionary.containsKey(key)) {
|
|
throw new BaseException("Key already exists in dictionary.");
|
|
}
|
|
|
|
dictionary.put(key, value);
|
|
}
|
|
|
|
public void update(K key, V value) throws BaseException {
|
|
if (!dictionary.containsKey(key)) {
|
|
throw new BaseException("Key does not exist in dictionary.");
|
|
}
|
|
|
|
dictionary.put(key, value);
|
|
}
|
|
|
|
public void remove(K key) throws BaseException {
|
|
if (!dictionary.containsKey(key)) {
|
|
throw new BaseException("Key does not exist in dictionary.");
|
|
}
|
|
dictionary.remove(key);
|
|
}
|
|
|
|
public V get(K key) throws BaseException {
|
|
if (!dictionary.containsKey(key)) {
|
|
throw new BaseException("Key does not exist in dictionary.");
|
|
}
|
|
|
|
return dictionary.get(key);
|
|
}
|
|
|
|
public boolean contains(K key) {
|
|
return dictionary.containsKey(key);
|
|
}
|
|
|
|
public String toString() {
|
|
var sb = new StringBuilder();
|
|
for (var key : dictionary.keySet()) {
|
|
sb.append(key);
|
|
sb.append(" --> ");
|
|
sb.append(dictionary.get(key));
|
|
sb.append("\n");
|
|
}
|
|
return sb.toString();
|
|
}
|
|
|
|
public Collection<V> getContent() {
|
|
return dictionary.values();
|
|
}
|
|
|
|
public IDictionary<K, V> copy() {
|
|
var newDictionary = new GenericDictionary<K, V>();
|
|
for (var key : dictionary.keySet()) {
|
|
newDictionary.dictionary.put(key, dictionary.get(key));
|
|
}
|
|
return newDictionary;
|
|
}
|
|
}
|