我必须编写一个哈希表,它使用数组索引中的链接来将多个值存储在同一位置,而不是线性探测。 然而,在这个测试中,我的链表数组似乎充满了空值,但当我尝试调用链表方法时,我得到了 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);
}
}
然后是链表类 封装链表;
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++;
}
最佳答案
您实例化了 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]);
}
当您尝试调用 size 时,您的
。NullPointerException
来自行 System.out.println(testArray[0].size());
空对象的 ()
关于java - 如何创建使用方法的链接列表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29783926/