在下面的代碼中,interface Dictionary
有一些使用Object
類型作爲參數的方法。本字典代碼中是否需要Java泛型?
/* Dictionary.java */
package cs61b.homework6.dict;
public interface Dictionary {
public int size();
public boolean isEmpty();
class Entry {
protected Object key;
protected Object value;
public Object key() {
return key;
}
public Object value() {
return value;
}
}
public Entry insert(Object key, Object value);
public Entry find(Object key);
public Entry remove(Object key);
public void makeEmpty();
}
下面
是實施interface Dictionary
class HashTableChained
,
/* HashTableChained.java */
package cs61b.homework6.dict;
import java.util.ArrayList;
import java.util.Iterator;
import JavaCollections.list.DblyLinkList;
public class HashTableChained implements Dictionary {
private long tableSize;
private ArrayList<DblyLinkList<Entry>> defTable;
public HashTableChained(long sizeEstimate) {... }
public HashTableChained() { ... }
private static boolean isPrime(long n) { ...}
private static long nextPrime(long previous) { .. }
int compFunction(int code) { ... }
public int size() { ... }
public boolean isEmpty() { ... }
public Entry insert(Object key, Object value) { ... }
public Entry find(Object key) { ... }
public Entry remove(Object key) { ... }
public void makeEmpty() { ...}
}
我想了解,是否有引進interface Dictionary<K, V>
語法與K key
和V value
的優勢呢?
注:Java初學者。完整的代碼可用here。老師鼓勵編寫自己的包,而不是使用java.util
收集包。
..類型安全? –
爲什麼你不實現java.util.Map接口? –
由於你在'Entry'中看起來沒有'Key'和'Value'的setter,所以來自泛型的類型安全性不會是編譯時的那種helpfull。 – SomeJavaGuy