Java - Null pointer exception

I hate Java, btw. I can never find where errors are happening because everything has to be abstracted in Java. Whatever, I guess it's good practice. Anyway, I can't find where the null pointer exception is occurring here. I've ran through it on paper and it should work out fine, so I think it's just a flawed understanding of Java. This is a method for a linked list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public boolean insert(int n, E e) {
        if(n < 0 || n > size) return false;
        
        Node node = new Node();
        node.data = e;
        
        Node current = head;
        Node prev = null;
        for(int i = 0; i < n; i++) {
            prev = current;
            current = current.next;
        }
        prev.next = node;   //Supposedly occurring here when 
        node.next = current;
        size++;
        return true;
    }

The actual output for this doesn't make sense. Supposedly it's happening between two statements, but both are executing fine? I'm pretty much lost here.
What if n == size == 0? Wouldn't head be null?
That's something I hadnt thought of. Still happening with that fixed, though.
closed account (18hRX9L8)
ResidentBiscuit wrote:
I hate Java, btw. I can never find where errors are happening because everything has to be abstracted in Java.

Yes, I agree with you. You get a lot of warnings, especially when you are using Eclipse.
closed account (o1vk4iN6)
1
2
3
4
5
6
Node prev = null;
for(int i = 0; i < n; i++) {
     prev = current;
     current = current.next;
}
prev.next = node;   //Supposedly occurring here when 


If n is zero prev is always null.

 
Node prev = current;


Instead maybe?
There it was. That just got rid of the null pointer exception. I had thought of that earlier, but for some reason I thought doing so would make prev and current always the same. Not sure where that line of thought came from. Anyways, thanks! I appreciate it to all who helped.

EDIT:
Actually, somehow that created a loop in the list.
Last edited on
Topic archived. No new replies allowed.