Reputation: 1089
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 .
Upvotes: 1
Views: 339
Reputation: 3275
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.
Upvotes: 1