为什么.clear()
即使在放入 HashMap 后也会销毁我的对象列表,而不是仅仅创建该对象的新实例?
变量声明:
List<Pricing_Data> toAdd = new ArrayList<Pricing_Data>();
HashMap<String, List<Pricing_Data>> pricingMap_twelve = new HashMap<String, List<Pricing_Data>>();
按预期工作的示例:
pricingMap_twelve.put(pricing.get(y).getName(), toAdd);
toAdd = new ArrayList<Pricing_Data>();
添加到 HashMap 后, HashMap 中的数据发生意外破坏的示例:
pricingMap_twelve.put(pricing.get(y).getName(), toAdd);
toAdd.clear();
我猜这与我第一次处理日历时遇到的类似问题有关,其中数据实际上并未“放入”对象中,而是指向原始数据的指针?
最佳答案
当使用toAdd.clear
时方法,您将清除 toAdd
所持有的列表的当前引用的内容变量。
当使用toAdd = new ArrayList<Pricing_Data>()
时,现在toAdd
变量指向一个新的引用。 toAdd
持有的旧引用仍将存储在 pricingMap_twelve
的引用保持中.
更多信息:
关于java - 清除列表与新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26391549/