链表数组总是给出 NullPointerException

Array of LinkedLists always gives NullPointerException

我正在创建自己的 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);
    }
}

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

size = buckets.length;

进入循环之前