Java:更改对象值而不更改所有引用 [英] Java: Change an objects value without changing all references

查看:59
本文介绍了Java:更改对象值而不更改所有引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个菜鸟问题,但我就是不明白.

我正在尝试在我的游戏中实现 A* 寻路.我正在关注 本教程AstarPathfinder.java 中的代码.但是,我没有实例化 AStarPathfinder 类并为所有 Nodes 设置一个 2D 数组,而是创建了一个静态方法,将我的 2D 数组(关卡/世界)、开始和结束节点传递给该方法.因此,我总是必须将当前和下一个 Node 存储在 Node nextNode current 中.然后我将它们添加到打开或关闭列表(取决于它们所属的位置)并使用它们的 setter 方法更改 Node 的 x 和 y 值(位置),以获得下一个节点.>

经过几分钟的调试,我注意到这个 (ofc) 也改变了 openListclosedList 中节点的值.为了防止这种情况,我可以简单地调用 next = new Node(int x, int y) 而不是只设置值,但是由于我的 Pathfinding 每隔几个渲染循环运行一次,它会搞乱垃圾收集和成本很多性能.所以我正在寻找一种可能性,有一个 Node 变量,我可以用默认构造函数实例化一次,然后改变它的值而不改变它在列表中的值.

这有可能吗?

解决方案

虽然这不能直接回答您的问题,但希望它能帮助您做出正确的决定

JVM 已经变得非常擅长重用对象,您通常不应该害怕使用 new 关键字.

更详细的阅读,请参见should-we-avoid-object-在java中创建

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

这篇关于Java:更改对象值而不更改所有引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆