【问题标题】:How do I make an array of Linked Lists that uses methods如何制作使用方法的链接列表数组
【发布时间】:2015-04-21 21:59:21
【问题描述】:

我必须编写一个哈希表,它使用数组索引中的链接来将多个值存储在同一个地方,而不是线性探测。 然而,我的链表数组在这个测试中似乎充满了空值,但是当我尝试调用链表方法时,我得到了一个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++;
    }

【问题讨论】:

  • 请发布堆栈跟踪。
  • 对象引用数组使用null 元素进行初始化。您必须手动初始化每个元素,例如在 for 循环中。
  • “我的链表数组在这个测试中似乎充满了空值,但是当我尝试调用链表方法时出现 NullPointerException” 你不明白什么确切地?你认为null 是什么意思? stackoverflow.com/questions/218384/…
  • 谢谢大家!是的,我通过制作一个 shell 列表来实现它,因为 Java 和 Luiggi 建议需要这样做,所以现在制作表格时会生成每个 LList。

标签: java arrays hash linked-list chaining


【解决方案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]);
}

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

【讨论】:

    猜你喜欢
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多