【问题标题】:Array of LinkedLists always gives NullPointerExceptionLinkedLists 数组总是给出 NullPointerException
【发布时间】:2020-07-20 20:32:16
【问题描述】:

我正在创建自己的 HashSet 实现以供练习。每次我将任何内容添加到我的链表数组时,我都会得到一个 NullPointerException

我什至尝试在每个数组索引中使用一个值启动LinkedList(只是为了调试),但我仍然收到异常错误。

public class MyHashSet {

    protected int size;
    private int currentSize;
    protected LinkedList<Integer>[] buckets; //array of linked list
    
    private double loadFactor = 0.75;
    
    /** Initialize your data structure here. */
    @SuppressWarnings("unchecked")
    public MyHashSet() {
     
    buckets = new LinkedList[4];
        for(int i = 0; i< size; i++){
            LinkedList<Integer>  ll = new LinkedList<Integer>();
            ll.add(0);  //I will remove this but  just to see what might happen - but still get error
            buckets[i] = ll;
           
        }
        size = buckets.length;
        this.buckets = buckets;
        System.out.println(buckets[1].isEmpty());  // I GET ERROR HERE NULLPOINTEREXCEPTION
    }


//..........I've removed most of my other methods just for the questions

    public static void main(String[] args) {
        MyHashSet hash = new MyHashSet();
        //hash.add(5);
    }
}

【问题讨论】:

    标签: arrays linked-list nullpointerexception hashset


    【解决方案1】:

    您的 size 变量在循环之前未初始化。它的默认值为零,因此 buckets[1] 不会被初始化。 试试放

    size = buckets.length;
    

    进入循环之前

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多