Search code examples
javaobjectarraylistcoordinatespath-finding

Changing a variable in an Object from an ArrayList<Object>


I am currently trying to create a pathfinding method for my grid based game based on the A* method algorithm. However I am having a basic problem with manipulating variables within my PathNode class instances:

public void AStarPathfinding(PathNode snakeHead, PathNode foodLocation) {

    System.out.println(food.xFood);
    System.out.println(food.yFood);

        openNodes.add(snakeHead);

        int xHead = (int) snakeSegments.get(0);
        int yHead = (int) snakeSegments.get(1);


        snakeHead.xCoordinate = (int) xHead;
        snakeHead.yCoordinate = (int) yHead;
        foodLocation.xCoordinate = (int) food.xFood;
        foodLocation.yCoordinate = (int) food.yFood;

however I am receiving null-point exception errors:

Exception in thread "Thread-2" java.lang.NullPointerException
    at ArtificialSnake.AStarPathfinding(ArtificialSnake.java:136)

which is this line:

snakeHead.xCoordinate = (int) xHead;

The idea is to set the startNode(snakeHead) to the current snake head's location.... but as suggested above I cannot work out how to modify the xCoordinate variable in the snakeHead instance of the PathNode class.

Looking at another question: Edit variables from object in ArrayList?

It suggests using setters, I have tired this however I still get null point exception errors.

Note: the Thread2 is the gameLoop thread separate from the Swing U.I, the class that this pathfinding method is in is part of the same thread.

What am I missing here?


Solution

  • If you receive a null pointer error on the line snakeHead.xCoordinate = (int) xHead; this means that snakeHead is null, check that null isn't being passed into the method. If your wonderhy why a null pointer error doesn't occur at openNodes.add(snakeHead); it is because null can be added to some java collections, they don't all try to perform any operations on what you pass to them (those that do may call hashCode(), equals() or compare() depending on the collection type and it's implementation).

    When you pass objects between methods and into collections/arrays you are making shallow copies (You are passing a reference to the object) so any changes you make to the object, will be visible in every other place you've passed the reference.

    The only way to make a deep copy of an object (so that changes don't affect other references to the object) is to copy every member variable of the object (some classes may provide a clone method that does this).