0

I have

 public Object get(int index)
    {
        if (index <= 0)
            return null;

        Node Current = head.getNext();
        for (int i = 1; i < index; i++) {
            if (Current.getNext() == null)
                return null;

            Current = Current.getNext();
        }
        return Current.getData();
    }

this method for a linked list to get something in an index. That something is a Painting object, and I want to get the title of the painting using a getTitle method within the Painting class.

Here is what I tried to do,

for(int i = 0; i < paintings.size(); i++){
        Painting x = (Painting) paintings.get(i);
        System.out.println((i+1) + ": " + x.getTitle());
}

Unfortunately at x.getTitle() java gets extremely salty and gives a null pointer exception. I've tried multiple ways of doing this with different casts and I'm just personally lost. Any help would be deeply appreciated.

Man Person
  • 1,122
  • 8
  • 20
  • 34

2 Answers2

2

You should have a validation since x can be null. When x=null, x.getTitle() become null.getTitle() which cause NullPointerException.

 Painting x = (Painting) paintings.get(i);
 System.out.println((i+1) + ": " + (x!=null?x.getTitle():"x is null"));
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • Actually I've realized my real issue was that my linkedlist's first index is actually 1 instead of 0, but this also helps incase the linked list is empty and the user prints out the contents of it so thanks. – Man Person Sep 26 '14 at 13:29
2

You are returning null if nothing is present at that index, and then doing x(null).getTitle() causing NullPointerException.

Just add a null check before calling the method.

codingenious
  • 8,385
  • 12
  • 60
  • 90