Java: Change an objects value without changing all references

Deadly 提交于 2019-12-11 09:23:06

问题


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?


回答1:


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




回答2:


What you're looking for is not possible. You only have one instance of a Node object, with pointers to that object in multiple locations. You need to make new Node instances.

it would mess up garbage collection and cost a lot of performance

If you haven't done performance testing and shown that this is an unacceptable bottleneck, you should not assume this.



来源:https://stackoverflow.com/questions/22354115/java-change-an-objects-value-without-changing-all-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!