1

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 .

5
  • 1
    Yes create a class which extends Map, and override the methods to print what you want Commented Aug 10, 2017 at 13:28
  • Can you better explain what do you need? Commented Aug 10, 2017 at 13:48
  • 1
    You could just extend HashList to record your changes as they come, print them or store them. I added a basic implementation below. Commented Aug 10, 2017 at 15:55
  • @shashantrika, if the answer below was useful, may I ask you accept it? Commented Aug 17, 2017 at 10:42
  • @shashantrika, why did you un-accept? Is there anything I can do to add to the solution? Commented Aug 17, 2017 at 12:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.