【问题标题】:Hashmap updating for all keys if value is updated for a particular key如果为特定键更新值,则更新所有键的哈希图
【发布时间】:2019-04-25 11:24:01
【问题描述】:

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

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

这是我的代码

最初的日期是这样设置的

   // 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);
            }
        }

然后将结束日期更新为 null 仅适用于 101

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);                                        
            }
        }

初始 dateMap 响应

{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]}

当我更新为 null 之后,

{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]}

【问题讨论】:

  • @Deadpool,我更新了关于如何设置日期的代码。我觉得日期列表的引用有问题
  • 恰好为您配对相同值的每个键
  • @Deadpool,那我应该在哪里修改代码?

标签: java hashmap


【解决方案1】:

问题在于你要配对相同列表对象的每个键,在 for 循环中每次使用 new ArrayList(Collection&lt;? extends E&gt; 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(Collection c)

按照集合的迭代器返回的顺序构造一个包含指定集合元素的列表。

【讨论】:

  • resultDate 本身就是一个List对象,要我再把List的新ArrayList放上来?
  • 为什么我们需要这段代码 --dateMap.get(Integer.parseInt(record));??您没有以任何方式对其进行初始化?
  • 是的,你可以删除不需要的代码,我只是想解决这个问题@Syed
【解决方案2】:

您的值可能使用一个带有差异别名的列表

List one = new AraayList();
map.put("k1", one);
map.put("k2", one);
List alias = one;
map.put("k3", alias);

这些值使用相同的实例,当您更新一个时,其他的会看到更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-08
    • 2011-05-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多