如何创建使用方法的链接列表数组

时间:2015-04-21 21:59:21

标签: java arrays hash linked-list chaining

我必须编写一个哈希表,它在数组索引中使用链接在同一个地方存储多个值而不是线性探测。 但是,我的链接列表数组似乎在此测试中实例为空,但是当我尝试调用链表方法时,我得到NullPointerException。我和我的教授都无法弄明白为什么。

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

import Hash.*;
import LinkedList.*;

public class Main {

    public static void main(String[] args) {
LList<Integer>[] testArray = (LList<Integer>[]) new LList<?>[5];
        for(int i=0;i<5;i++)
            System.out.println(testArray[i]);

        System.out.println(testArray[0]);
        System.out.println(testArray[0].size());
        testArray[0].add(40);
        }
    }

然后是Linked List类     package LinkedList;

public class LList<T> implements I_LList<T> {
    protected int numElements;
    protected boolean found;

    protected LLNode<T> current;
    protected LLNode<T> previous;
    protected LLNode<T> list;

    public LList(){
        list = null;
        current = null;
        numElements = 0;
    }
    public void add(T element){
        System.out.println("LList add()");
        LLNode<T> newNode = new LLNode<T>(element);
        newNode.setLink(list);
        list = newNode;
        numElements++;
    }

1 个答案:

答案 0 :(得分:1)

您实例化LList个对象的数组,但不实例化每个LList个对象。

LList<Integer>[] testArray = (LList<Integer>[]) new LList<?>[5];
for(int i=0;i<5;i++)
{
    testArray[i] = new LList<Integer>(); // add this line
    System.out.println(testArray[i]);
}

当您尝试调用空对象的NullPointerException时,System.out.println(testArray[0].size());来自行size()