简体   繁体   中英

"If" makes NullPointerException

I'm writing program, which do some operations with doublylinked lists(my implementation). There is one thing which i do not understand and it confusing me a lot.

Ok. So. I have two doubly linked list. I need to create method where argument is a index of first doublylinked list, and on that index i need to put second list.

I wrote that method:

    public void PutInPlace(int i){
        DoublyLinkedList ldw3 = new DoublyLinkedList(); // New doublylinked list.
        Node current = ldw1.tail; // ldw1 - First doublylinked list, created earlier.
        Node current1 = ldw2.tail;  //ldw2 - Second doublylinked list, created earlier.
        int counter = 0;

        while(true){
           ldw3.AddHead(current.number);
           current = current.prev;
           counter++;
           if(counter == i){  // THAT if makes NullPointerException

            ldw3.AddHead(current1.liczba);
            current1 = current1.prev;
            if(current1 == null)
                break;

        }
     }

I dont wanna put all code, because it is long and can be not-easy to read. So, why "if(counter == i)" makes NullPointerException? Without that "if" program works. Where is the problem?

Thank you for help, guys!

current1 may be null. But you are trying to get the value

if(current1 != null)
{
   ldw3.AddHead(current1.liczba);
   current1 = current1.prev;
}

instead of

current1 = current1.prev;

(or)

change the statement like this,

if(current1 == null)
   break;
ldw3.AddHead(current1.liczba);
current1 = current1.prev;

instead of

ldw3.AddHead(current1.liczba);
current1 = current1.prev;
if(current1 == null)
   break;

I think the current variable is the one being null. The i variable has a unique value, let's say 3.

While(true) is an infinite loop, and your condition (counter==i) will be executed only once (since you always increment counter and it will hit the value 3 only once). So unless current1 has no previous, the break will never be it and you will arrive to a point where current has no more previous (making it null and giving an exception when doing current.prev)

A good practice is always checking if an object is null before using one of its methods or attributes.

No, that "if" cannot make a NullPointerException.

First, make sure you recompile everything, and run a test. Then post the output from that test, including the stack trace from the exception.

Second, post the source code verbatim (so the line numbers are clear).

Third, post the javap output for the PutInPlace method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM