gpt4 book ai didi

java - 我如何确定何时可以重用对象?

转载 作者:行者123 更新时间:2023-12-02 11:42:47 24 4
gpt4 key购买 nike

假设我有以下代码片段来为我正在制作的小型随机游戏创建彩色蔬菜,以练习将对象属性从对象类中分离出来:

    List<Vegetable> vegList = new ArrayList<Vegetable>();

Map<MyProperty, Object> propertyList = new HashMap<MyProperty, Object>();

propertyList.put(MyProperty.COLOR, "#0000BB");
propertyList.put(MyProperty.TYPE, MyType.VEGETABLE);
propertyList.put(MyProperty.COMMONNAME, "Potato");

vegList.add(new Vegetable("Maisie", propertyList));

propertyList.put(MyProperty.COLOR, "#00FF00");
propertyList.put(MyProperty.COMMONNAME, "Poisonous Potato");

vegList.add(new Vegetable("Horror", propertyList));

我在这样做时意识到(基本上,我自己的例子来自 Head First OOA&D)我不知道为什么第二次更改 propertyList 不会影响 Maisie 中先前设置的值。

我遵循了本书提供的结构,但第一次我是为每个单独的 Vegetable 对象创建一个新的 HashMap,然后再将其添加到列表中。这本书表明这是不必要的,但没有详细说明原因。

我所看到的是,当第二次在 Vegetable 构造函数中指定 HashMap 时,解释器正在选择创建 HashMap 的新实例。但是为什么

它怎么知道我宁愿在那里有一个不同的 HashMap,而不是重用第一个对象并 .put() 更改两个 Vegetables 的值?

<小时/>

第二个相关问题是......我是否应该让两种蔬菜共享完全相同的属性列表(相同的 HashMap 对象),我该怎么做?这实际上是一个可怕的想法......为什么?我不知道自己在做什么,怎么会想要这个节目呢?

我的理解超出了“它与对象引用有关”的范围。

感谢您帮我解决这个问题。

<小时/>

根据要求蔬菜类:

public class Vegetable {
public VegetableSpec characteristics;
public String name;

public Vegetable(String name, Map<MyProperty, Object> propertyList) {
this.name = name;
this.characteristics = new VegetableSpec(propertyList);
}

public void display() {
System.out.printf("My name is %s!\n", this.name);
for (Entry<MyProperty, Object> entry : characteristics.properties.entrySet()) {
System.out.printf("key: %s, val: %s\n", entry.getKey().toString(), entry.getValue().toString());
}
}
}

...这让我再次查看 VegetableSpec (我把它放进去是因为这本书使用了一个单独的 Spec 类,但我不明白为什么除了添加搜索功能之外还有必要;现在我想我看到它做了 2事情,其中​​之一是防御性复制!):

public class VegetableSpec {
Map<MyProperty, Object> properties;

public VegetableSpec(Map<MyProperty, Object> properties) {
if (properties == null) {
// return a null = bad way to signal a problem
this.properties = new HashMap();
} else {
// correction above makes it clear this isn't redundant
this.properties = new HashMap(properties);
}

}

}

最佳答案

听起来 Vegetable 的构造函数正在创建 defensive copy 。这样做通常是一个好主意,可以防止任何人以对象设计者不希望的方式更改对象。你应该(几乎)总是制作防御性副本。

I want to actually have 2 vegetables share the exact same list of properties (the same HashMap object), how would I do that?

传递相同的 HashMap ,并忽略它创建防御性副本的事实,对于作为消费者的您来说应该不重要。

关于java - 我如何确定何时可以重用对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48426502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com