1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java NullPointerException

  1. Aug 7, 2011 #1
    For the following segment of code, I am getting a null pointer exception when trying to access any value in a list (doubly-linked with dummy nodes) AFTER a null value. For example, if I have the following list of integers:

    0, 1, 2, 3, null, 4, 5

    and I run the function list.contains(0) or list.contains(1)...list.contains(null), the program works as it should. When I try to call list.contains(4) or list.contains(5), I receive a null pointer exception. I know the order in which I use == and .equals() matters, but should I separate it into multiple if statements? I tried to do so, and I was not receiving any different results.

    for (Node cursor = _head._next; cursor != _tail; cursor = cursor._next){
    if ((o == null & cursor._data == null) || cursor._data.equals(o)) // o is the Object data
    return true;
     
  2. jcsd
  3. Aug 7, 2011 #2

    I like Serena

    User Avatar
    Homework Helper

    Hi magnifik! :smile:

    You cannot use the function cursor._data.equal() if cursor._data is a null pointer.
    Your current code does not prevent this (which manifests when you have o=4).

    I recommend turning it into an if-statement where you just check if cursor._data is a null pointer, and then take appropriate action.
     
  4. Aug 7, 2011 #3
    You can also consider using a try-catch statement similar to this:
    Code (Text):

    try {
        cursor._data.equals(o)
    }
    catch (NullPointerException e) {
        System.out.println("NullPointerException thrown");
    }
    I'm presuming that "I like Serena" is correct in that the exception is being caused by cursor._data.equal().
     
  5. Aug 8, 2011 #4
    thank you for the suggestion! my program functioned correctly after using a series of if statements rather than my single one :)
     
  6. Aug 8, 2011 #5

    I like Serena

    User Avatar
    Homework Helper

    Good! :smile:

    And here's one for the road:

    Code (Text):

    bool found = false;
    for (Node cursor = _head._next; (cursor != _tail) && !found; cursor = cursor._next)
    {
       // o is the Object data
       if (cursor._data == null)
       {
          found = (o == null);  
       }
       else
       {
          found = cursor._data.equals(o);
       }
    }
    return found;
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java NullPointerException
  1. Java program (Replies: 3)

  2. Java prob. (Replies: 1)

  3. HeapSort Java (Replies: 3)

Loading...