Search code examples
javapriority-queuetraveling-salesman

PriorityQueue poll() throwing NullPointerException


I am working with a priority queue in Java for the first time and I can't for the life of me understand what I am doing that is leading to the exception. I'm attempting to implement an ant colony type solution to the traveling salesman problem. The following is the only code being called for my AntColony class.

public AntColony(TSPInstance p) {
    PriorityQueue<Ant> ants = new PriorityQueue<Ant>(new AntComparator());
    size = p.getDimension();
    for (int i = 0; i < size; i++) {
        ants.offer(new Ant(p));
    }
    shortestTour = Integer.MAX_VALUE;
}

public void nextMove() {
    ants.poll();
}

The code that I'm running afterwards just as a test is as follows (just in a main method).

AntColony a = new AntColony(p);
a.nextMove();

The a.nextMove() throws a NullPointerException at the ants.poll() part, but yet if I change the constructor to (for debugging purposes)

public AntColony(TSPInstance p) {
    PriorityQueue<Ant> ants = new PriorityQueue<Ant>(new AntComparator());
    size = p.getDimension();
    for (int i = 0; i < size; i++) {
        ants.offer(new Ant(p));
    }
    ants.poll(); //ADDED THIS
    shortestTour = Integer.MAX_VALUE;
}

and then just do

AntColony a = new AntColony(p);

I don't get an exception. I'm struggling to understand how I'm getting an exception from ants.poll(), but yet when I call it from the constructor everything works. Any help with this would be appreciated. There's a lot of code for various things in this project, so I didn't think uploading it all would help anybody so let me know if there's something I should include, but I don't see how the problem could lie outside these two bits of code.

Added: Actual exception

Exception in thread "main" java.lang.NullPointerException
at data_structures.AntColony.nextMove(AntColony.java:25) (the ants.poll() part)
at algorithms.ACTest.main(ACTest.java:6) The a.nextMove() part

Solution

  • The ants variable in your AntColony constructor is a local variable. So when you exit the constructor, it no longer exists. Apparently the ants variable that your nextMove method is calling, is a class member.

    You need to change your constructor to have:

        // initialize the class member, not a local instance.
        ants = new PriorityQueue<Ant>(new AntComparator());