1

So, I'm having a bit of issue with my code here. I'm getting an error at

if(Front.data==null)

Exception in thread "main" java.lang.NullPointerException at DoubleLinky.insert(DoubleLinky.java:17)

How do I fix this, I'm actually having a very hard time learning how double linked list works.

public class DoubleLinky<AnyType> implements DoublyLinkedList<AnyType>
{

    private MyDoubleNode<AnyType> Front = null;
    MyDoubleNode<AnyType> Tail  = new MyDoubleNode<AnyType>();


    public void insert(AnyType x) 
    {
        if(lookup(x)==true)
            return;

        if(Front.data == null)
        {
            Front.data = x;
            return;
        }

        if(Tail.data == null)
        {
            Tail.data = x;
            return;
        }

        MyDoubleNode<AnyType> A = Front;
        MyDoubleNode<AnyType> C = Tail.next;
        MyDoubleNode<AnyType> B = new MyDoubleNode<AnyType>(x, C, A);
        A.next = B;
        C.prev = B;

    }
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • @SotiriosDelimanolis Well, maybe this question is a duplicate on your level, but it isn't on the level of OP. If he would be on your skills, he didn't have to open this question. In my opinion, you are now on a closing spree. – peterh Sep 21 '15 at 00:28
  • @peterh The duplicate is what we call a _canonical answer_. This question is asked every day, multiple times. We're not going to start answering every occurrence. The canonical answer explains what a NPE is and how to debug it. That's all you should need. Unless there's something extremely obscure about the code that throws it, there's no reason to have this duplicate. There is only one way `Front.data == null` can thrown a `NullPointerException`. – Sotirios Delimanolis Sep 21 '15 at 01:11
  • @peterh You can further discuss reasons to close as duplicate (or what counts as a duplicate) on Meta. – Sotirios Delimanolis Sep 21 '15 at 01:11

2 Answers2

1

This means that your Front object itself is null. You can fix this by checking first if your Front is null or not before accessing any member data from it. You try to access Front.date before giving Front a value later on in this method.

Amr
  • 792
  • 3
  • 15
1

At this line Front is initialized to null

private MyDoubleNode<AnyType> Front = null;

When you attempt to access a member :

if (Front.data == null)

you naturally get a NullPointerException

Front needs to be initialized before accessing its members. E.g.

private MyDoubleNode<AnyType> Front = new MyDoubleNode<AnyType>();

And at first glance, you probably want to initialize Tail to null. And then check if it is null before using it. E.g.

if (Tail != null && Tail.data == null)
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82