我在游戏中有一个用于统计的基础对象。每次我为战斗 map 上的 40 个总和单位开始战斗时,我都会复制该对象。
然后我修改每个单元的统计对象。我当然不想通过引用传递。基本统计对象包含大约 50 个基元。因此,我创建了该对象的构造函数类,并乏味地复制了每个原语。从我在谷歌搜索中发现的情况来看,这似乎是最安全的方法。
示例代码
class Stats{
int x;
int y;
int b;
public Stats(Stats stats)
{
this.x = stats.x;
this.y = stats.y;
this.b = stats.b;
}
}
Stats currentUnit = new Stats (currentUnitBaseStats);
-问题-
这非常令人沮丧和困惑。是否值得我花时间研究实现内置克隆功能?
如果我的stats类最终包含其他对象,那么其中包含的所有对象是否也需要实现克隆功能?
有没有更简单的方法?
附带问题:在 Android 上,持有 40 个独立类(每类 100 个基元)的 RAM 消耗仍然相当低,对吧? 谢谢,我爱你们:)
最佳答案
如果你有这么多原语(50)为什么不使用 HashMap ?:
public static void main (String[] args)
{
HashMap<String, Integer> stats = new HashMap<String,Integer>();
stats.put("x",3);
stats.put("y",4);
stats.put("z",5);
stats.put("b",9);
HashMap<String, Integer> statsCopy = new HashMap<String,Integer>();
statsCopy.putAll(stats);//this will copy all the values from the base object
}
关于java - 关于新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20438179/