LinkedLists数组总是给出NullPointerException



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

我甚至尝试在每个数组索引中用一个值初始化LinkedList(只是为了调试(,但我仍然收到Exception错误。

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);
}
}

您的大小变量在循环之前没有初始化。它的默认值为零,因此bucket[1]不会初始化。尝试放置

size = buckets.length;

进入环路之前

相关内容

  • 没有找到相关文章

最新更新