2

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

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

I haved added code to check ptr is not null in find(). But it is still causing Null Pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.