This is probably a noob question, but i just don't get it.
I am trying to implement A* pathfinding in my game. I was following this tutorial and the code in the AstarPathfinder.java
. But instead of instantiating the AStarPathfinder class and having an 2D Array for all Nodes
i made a static method, to which i pass my 2D Array (the Level/World), start and end Node.
Cause of this i always have to store the current and the next Node
in a Node next
and Node current
. I then add them to the open or closed list (depends on where they belong) and change the x and y value (position) of the Node
with their setter method, to have the next node.
After a few minutes of debuging i noticed that this (ofc) changes also the value of the node inside the openList
and closedList
. To prevent this i can simply call next = new Node(int x, int y)
instead of only setting the values, but as my Pathfinding is running every few render loops it would mess up garbage collection and cost a lot of performance. So i am looking for a possibility to have one Node
variable, which i can instantiate once with default constructor, and then change its value without changing its value in the list.
Is that possible somehow?
While this is not a direct answer to your question, hopefully it will help you make a good decision
The JVM has become very good at re-using objects and you should generally not be afraid to use the new keyword.
For more detailed reading, see should-we-avoid-object-creation-in-java