What is causing Null Pointer Exception in the following code in java? [migrated]
- by Joe
When I run the following code I get Null Pointer Exception. I cannot figure out why that is happening. Need Help.
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);
}
}