在下面的代码中,interface Dictionary
有一些方法使用Object
类型作为参数。
/* 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();
}
以下是class HashTableChained
的实施interface Dictionary
,
/* 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
集合包。
答案 0 :(得分:5)
有一个优点。通过验证您没有做任何完全错误的事情(比如输入错误类型的密钥或值),它将在编译期间保证您的安全(r)。
在使用地图时,它还会删除(大部分)代码中的强制转换。
如果您使用Entry
Object
作为进行字数统计的键和值:
Dictionary dict = new Dictionary();
dict.insert("word", new Integer(42));
Object count = dict.find("word"); // gives an Object, not an Integer
// need to cast - annoying, not safe
Integer countAsInteger = (Integer)count;
如果你介绍泛型:
Dictionary dict = new Dictionary<String, Integer>();
dict.insert("word", new Integer(42));
Integer count = dict.find("word"); // gives an Integer
通用类型还可以保护您免于创建异构映射。在您的实现中,这是允许的:
dict.insert("word", "42");
但这可能是一个错误。您希望计数为Integer
。
在通用实现中,您将能够实现:
public void insert(K key, V value);
在地图中不允许(在编译时)除K
和V
之外的任何内容。