LinkedList哈希表中出现Null指针异常



所以我使用乘法方法创建了一个带有LinkedLists的哈希表。作为一个实例变量,我定义了将要使用的LinkedList"T",并在类的构造函数中指定了T的大小。然而,每次我运行Driver测试类时,我都会在T[]中尝试引用任何的内容上获得NullPointerException。我是不是忽略了什么?我花了一个多小时试图弄清楚。

ChainedHashTable类:

public class ChainedHashTable
{
    private LinkedList<Integer>[] T;
    private int m;
    private double A;
    public ChainedHashTable(int n)
    {
        for (m = 1; m < n; m *= 2);
        T = new LinkedList[m];
        Random random = new Random();
        int s = random.nextInt(Integer.MAX_VALUE);
        A = (s * 1.00) / Integer.MAX_VALUE;
    }
    public void insert(Integer key)
    {
        T[hash(key)].add(Integer.valueOf(key));
    }
    public void delete(int key)
    {
        T[hash(key)].remove(Integer.valueOf(key));
    }
    public Integer search(int key)
    {
        int n = T[hash(key)].indexOf(key);
        if (n == -1)
            return -1;
        else
            return T[hash(key)].get(n);
    }
    private int hash(int key)
    {
        System.out.println((int)(m * ((key * A) % 1)));
        return (int)(m * ((key * A) % 1));
    }
    public void printTable()
    {
        for (int i = 0; i < T.length; i++)
        {
            System.out.println("index: " + i + " " + T[i]);
        }
    }
}

驱动程序类别:

public class Driver
{
    public static void main(String[] args)
    {
        ChainedHashTable test1 = new ChainedHashTable(20);
        test1.printTable();
        test1.insert(4);
        test1.insert(54);
        test1.insert(6);
        test1.insert(3);
        test1.insert(26);
        test1.insert(54);
        test1.insert(11);
        test1.insert(10);
        test1.insert(76);
        test1.insert(42);
        test1.insert(41);
        test1.insert(32);
        test1.insert(87);
        test1.insert(76);
        test1.insert(72);
        test1.insert(57);
        test1.insert(29);
        test1.insert(16);
        test1.insert(92);
        test1.insert(64);
        test1.printTable();
    }
}

您正在创建一个引用数组以键入LinkedList,并将它们设置为初始状态,即null

T = new LinkedList[m];

CCD_ 5现在是计算出的大小为CCD_。您需要初始化数组内部的对象。

T = new LinkedList[m];
for (int i = 0; i < m; i++) {
    T[i] = new LinkedList<>();
}

最新更新