gpt4 book ai didi

java - 如果更新特定键的值,则更新所有键的 HashMap

转载 作者:行者123 更新时间:2023-11-30 01:51:32 25 4
gpt4 key购买 nike

我有一个 HashMap ,其中键为整数,值作为日期列表。我正在尝试更新特定整数的值之一。最初,所有 key 的日期都相同。

现在,我想将 101 键的日期之一设置为 null,当我更新特定键时,它会更新所有键。我哪里做错了?请建议。

这是我的代码

最初的日期是这样设置的

   // Set dates to all records
resultDate = [Mon Jan 01 00:00:00 IST 2018, Fri Dec 31 00:00:00 IST 9999] // Typo here
Set<Integer> records= parsedResults.keySet();
if (records.size() > 0) {
for (Integer record: records) {
dateMap.get(Integer.parseInt(record));
dateMap.put(record,resultDate);
}
}

然后仅将 101 的结束日期更新为 null

for (Map.Entry<Integer, List<Date>> entry : dateMap.entrySet()) {
if(entry.getKey().equals(Integer.parseInt("101"))) {
List<Date> dates = entry.getValue();
if(null == effDate) {
dates.set(0, null);
} else {
dates.set(0, effDate);
}
if(null == endDate) {
dates.set(1, null);
} else {
dates.set(1, endDate);
}
dateMap.put(Integer.parseInt("101"), dates);
}
}

初始日期映射响应

{101=[Mon Jan 01 00:00:00 IST 2018, Fri Dec 31 00:00:00 IST 9999], 102=[Mon Jan 01 00:00:00 IST 2018, Fri Dec 31 00:00:00 IST 9999], 103=[Mon Jan 01 00:00:00 IST 2018, Fri Dec 31 00:00:00 IST 9999]}

当我更新为空之后,

{101=[Mon Jan 01 00:00:00 IST 2018, null], 102=[Mon Jan 01 00:00:00 IST 2018, null], 103=[Mon Jan 01 00:00:00 IST 2018, null]}

最佳答案

问题是对于每个与相同列表对象配对的键,在 for 循环中使用 new ArrayList(Collection<? extends E> c)每次创建新对象的构造函数

if (records.size() > 0) {               
for (Integer record: records) {
dateMap.get(Integer.parseInt(record)); //you can remove this line
dateMap.put(record,new ArrayList(resultDate));
}
}

公共(public)ArrayList(集合c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

关于java - 如果更新特定键的值,则更新所有键的 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55841218/

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