1
votes

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 .

STAGE 1 :

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

Desired Result :
Added:
Key1 : Value1
Key2 : Value2
Key3 : Value3
Key4 : Value4

STAGE 2:

hashMap.remove("Key1");

Desired Result :
Removed:
Key1 : Value1

STAGE 3:

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

Desired Result :
Modified :
Key2 : ChangedValue

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

1
Yes create a class which extends Map, and override the methods to print what you wantazro
Can you better explain what do you need?Valerio Emanuele
You could just extend HashList to record your changes as they come, print them or store them. I added a basic implementation below.Assafs
@shashantrika, if the answer below was useful, may I ask you accept it?Assafs
@shashantrika, why did you un-accept? Is there anything I can do to add to the solution?Assafs

1 Answers

1
votes

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

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.