-2

我正在准备用 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) {
    }
}
4

1 回答 1

1

正如已经指出的那样,你错过了}你的hash方法的结束。但是,静态方法不能引用类的类型参数,否则会报错:

non-static class K cannot be referenced from a static context

但看起来该hash方法不需要是通用的。取而代之的是,它应该做得很好Object

public static int hash(Object key)
于 2013-03-07T01:36:45.373 回答