Results 1 to 2 of 2
  1. #1
    ScKaSx is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Thumbs up Null Pointer Exception

    Hi All,

    I am working on a code for linked lists and am encountering a strange null pointer exception error that I don't understand in the following code:

    Java Code:
    public class Node
    {
    	public Comparable item;
    	public Node next;
    
    	public Node(Comparable i)
    	{
    		item = i;
    		next = null;
    	}
    }
    
    private Node head;
    private Node iterator;
    
    public MySortedLinkedList()
    { 
    	head = null; 
    	iterator = null;
    }
    	
    public void add(Comparable item)
    {
            if (iterator == null) {
                     [B]head.item = item;[/B]
            }
    }
    I have test code that loads the linked list and when it tries to 'add' an element to the array the program stops on the bold statement, where I am trying to change the value of the head.item location to something other than null. Why do I get an exception here?

    Cheers,
    ScKaSx

  2. #2
    ScKaSx is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Default

    Hi All,

    For anyone that is curious about this, I found the solution. I thought I initialized the Node head when I wrote:

    Java Code:
    head = null;
    however, this did not create a new node. Therefore the correction for the bold statement would be:

    Java Code:
    head = new Node(item);
    How come coding can't always be intuitive?

    Cheers,
    ScKaSx

Similar Threads

  1. Null pointer Exception
    By peiceonly in forum New To Java
    Replies: 8
    Last Post: 09-05-2010, 06:48 PM
  2. Null Pointer Exception
    By Jacinth in forum New To Java
    Replies: 4
    Last Post: 01-22-2009, 01:47 PM
  3. Null Pointer Exception
    By demiser55 in forum New To Java
    Replies: 1
    Last Post: 09-22-2008, 06:33 PM
  4. null pointer exception
    By cityguy503@yahoo.com in forum New To Java
    Replies: 4
    Last Post: 08-22-2008, 07:22 PM
  5. getting a null pointer exception
    By Rjava in forum XML
    Replies: 4
    Last Post: 07-16-2008, 05:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •