我正准备通过编写Java中的各种数据结构进行访谈。我在静态上下文中遇到了泛型类型的麻烦。我有一个需要静态的哈希函数,它接受一个泛型参数,但编译器没有。任何关于为什么会发生这种错误的帮助,以及如何更好地解决问题。
public class Hashtable<K extends Comparable, T> {
private int num_elem;
private int num_buck;
private ArrayList<LinkedList<Pair<K, T>>> buckets;
private class Pair<K, T> {
K key;
T value;
Pair(K key, T value) {
this.key = key;
this.value = value;
}
}
public Hashtable(int size) {
this.num_elem = size;
this.num_buck = (int) (num_elem * 1.2);
this.buckets = new ArrayList<LinkedList<Pair<K, T>>>();
for (int i = 0; i < num_buck; i++)
buckets.add(new LinkedList<Pair<K, T>>());
}
public static int hash(K key) {
return (System.identityHashCode(key) * num_buck) / 97;
}
public static int compress(int hashval) {
return hashval % num_buck;
}
public void add(K key, T value) {
Pair p = new Pair<K, T>(key, value);
int hashval = Hashtable.hash(key);
buckets.get(Hashtable.compress(key)).add(p);
}
public T find(K key) throws exception {
int hashval = Hashtable.hash(key);
LinkedList<Pair<K, T>> ll = buckets.get(Hashtable.compress(hashval));
Iterator iter = ll.iterator();
while (iter.hasNext()) {
Pair<K, T> p = iter.Next();
if (p.key.compareTo(key) == 0)
return p.value;
}
throw new Exception("Key not in HashTable");
}
public void remove(K key) {
}
public static void main(String[] args) {
}
}
答案 0 :(得分:1)
正如已经指出的那样,您错过了}
方法的结束hash
。但是,静态方法不能引用类的类型参数,否则您将收到错误:
non-static class K cannot be referenced from a static context
但它看起来不像hash
方法需要是通用的。它应该很好地取代Object
:
public static int hash(Object key)