0

Why is there a null pointer exception error where prev.value.compareTo(v)<0 and if(cur.value.compareTo(v)<0 ?

public void insert (T v) {
        Node prev = head, cur = head.next;


        if(prev==null)
            {
            prev=head;

            }

        else if(prev.value.compareTo(v)<0)  //v belongs in the front
        {
            prev.value=v;
            prev=prev.next;
        }

        else
        {

            //iterate through the list
            prev=prev.next;
            cur=cur.next;
            while(cur!=null)
            {
                if(cur.value.compareTo(v)<0) 
                {
                    prev=cur;
                    cur=cur.next;
                }

            }

        }
}
forpas
  • 160,666
  • 10
  • 38
  • 76
  • 1
    In your code when `prev.value` or `cur.value` is null, it can not have a method `compareTo`, so it cannot be called, as the object is null. You can only call `compareTo` when the object where it's defined is not null. – dmitryro Nov 10 '18 at 19:25
  • make sure that `value` is referencing an object – The Scientific Method Nov 10 '18 at 19:26
  • This is where debugger would be useful. I wonder about this code `Node prev = head, cur = head.next; if(prev==null) { prev=head;` If prev is null, head must be null so this doesn't do anything – Peter Lawrey Nov 10 '18 at 19:42

0 Answers0