Katie Melosto
Katie Melosto

Reputation: 1177

Array of LinkedLists always gives NullPointerException

I'm creating my own HashSet implementation for practice. I'm getting a NullPointerException every time I add anything to my array of linked list.

I've even tried to initiate the LinkedList inside each array index with a value (just to debug) and I'm still getting the Exception error.

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

Upvotes: 0

Views: 40

Answers (1)

Fatima Hojeij
Fatima Hojeij

Reputation: 73

Your size variable is not initialized before the loop. It's default value is zero so buckets[1] will not be intialized. Try putting

size = buckets.length;

Before going into the loop

Upvotes: 1

Related Questions