Ishan
Ishan

Reputation: 4339

What is causing Null Pointer Exception in the following code in java?

When I run the following code I get Null Pointer Exception. I cannot figure out why that is happening.

public class LinkedList<T> {
private Link head = null;
private int length = 0;

public T get(int index) {
    return find(index).item;
}

public void set(int index, T item) {
    find(index).item = item;
}

public int length() {
    return length;
}

public void add(T item) {
    Link<T> ptr = head;
    if (ptr == null) {
        // empty list so append to head
        head = new Link<T>(item);
    } else {
        // non-empty list, so locate last link
        while (ptr.next != null) {
            ptr = ptr.next;
        }
        ptr.next = new Link<T>(item);
    }
    length++; // update length cache
}

// traverse list looking for link at index
private Link<T> find(int index) {
    Link<T> ptr = head;
    int i = 0;
    while (i++ != index) {
        if(ptr!=null) {
            ptr = ptr.next;
        }
    }
    return ptr;
}

private static class Link<S> {
    public S item;
    public Link<S> next;

    public Link(S item) {
        this.item = item;
    }
}

public static void main(String[] args) {
    new LinkedList<String>().get(1);
}
}

Upvotes: 2

Views: 227

Answers (2)

Dour High Arch
Dour High Arch

Reputation: 21712

new LinkedList<String>().get(1)

returns

find(1).item

find(1) returns head. But head is null, so you are returning

null.item

which is a Null Pointer Exception. You should check if find(index) is null in get.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

You never verify that ptr is not null in find().

Upvotes: 0

Related Questions