在特定状态下获取哈希图中新添加,删除,修改的值 [英] Getting the newly added , deleted , modified values in hashmap at a particular state

查看:66
本文介绍了在特定状态下获取哈希图中新添加,删除,修改的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,该应用程序分阶段对hashmap进行操作,从某种意义上说,它可以添加/删除/修改不同类中的键.关于通过扩展Map类来创建包装器类的思想.并破解预定义的放置和移除方法.

I have an application , which operates on the hashmap at stages , in the sense it adds/deletes/modifies keys in different classes . Thought of creating wrapper class by extending the Map class . And Hacking the predefined put and remove methods .

第1阶段:

HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("Key1","Value1");
hashMap.put("Key2","Value2");
hashMap.put("Key3","Value3");
hashMap.put("Key4", "Value4");

所需结果:
添加:
Key1:Value1
Key2:Value2
Key3:Value3
Key4:Value4

阶段2:

hashMap.remove("Key1");

所需结果:
已删除:
Key1:Value1

阶段3:

hashMap.put("Key2", "ChangedValue");

所需结果:
已修改:
Key2:ChangedValue

仅获取差异的最佳方法或最佳逻辑是什么?dataStructure HASHMAP是固定的.

What would be the best way or best logic to get only the diff ? The dataStructure HASHMAP is fixed .

推荐答案

最简单的方法是将HashMap扩展到您自己的类,并记录更改:

The simplest way is to extend HashMap to your own class, and record the changes:

class RecordHashMap extends HashMap<String,String> {
    private List<String[]> changes;

    public RecordHashMap() {
      super();
      changes = new ArrayList<String[]>();
    }

    @Override
    public String put(String key, String value) {

        if (containsKey(key)) {
            changes.add(new String[]{"modified",key,value});
        } else {
            changes.add(new String[]{"added",key,value});
        }
        return super.put(key, value);
     }

     @Override
     public String remove(Object key) {
         if (containsKey(key)) {
             String value = get(key);
             changes.add (new String[]{"removed",(String)key,value});
         }
         return super.remove(key);
     }

     public List<String[]> getChanges() {

         return changes;
    }
}

这样,您就可以始终检查上一次更改,因为它们都已记录下来.当然,您可以在录制时或以后将它们打印出来.您可以添加索引计数器(只允许查看x个最近的更改),因为您将它们存储在数组列表中.

This way you can always check the last change, as they are all recorded. You can of course print them out as you record them - or later. You can add an index counter (to allow to only look at x recent changes), since you store them in an array list.

这篇关于在特定状态下获取哈希图中新添加,删除,修改的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆