Java:在不更改所有引用的情况下更改对象值 [英] Java: Change an objects value without changing all references

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

问题描述

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

This is probably a noob question, but i just don't get it.

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

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.

调试几分钟后,我注意到此(ofc)也会更改openListclosedList内部节点的值.为了防止这种情况,我可以简单地调用next = new Node(int x, int y)而不是仅设置值,但是由于我的寻路工具正在运行每几个渲染循环,这会弄乱垃圾回收并降低很多性能.因此,我正在寻找具有一个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.

有可能吗?

推荐答案

虽然这不是您问题的直接答案,但希望它将有助于您做出明智的决定

While this is not a direct answer to your question, hopefully it will help you make a good decision

JVM已非常善于重用对象,因此您通常不必害怕使用 new 关键字.

The JVM has become very good at re-using objects and you should generally not be afraid to use the new keyword.

有关更多详细信息,请参见 should-we-avoid-object -creation-in-java

For more detailed reading, see should-we-avoid-object-creation-in-java

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

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