Reputation: 2849
I am using a TreeMap<Integer,Object>()
to store values.
Now my Object
has a component, Object.value()
, which keeps getting incremented as per values read from a file.
So, I evaluate whether the key exists and need to update value.
I do not understand how I can update values in a Map
in Java.
I cannot just replace the whole record, as new values need to be added to the existing record value.
Is there a better way to do this than using a map? I used a map because I will keep searching for the keys.
Any suggestions?
Upvotes: 1
Views: 10583
Reputation: 591
I'm not sure of what you are trying to do but if you just want to store objects with keys you should use a Hashtable. It allows to map keys to objects.
//create a hashtable
//the first template type is the type of keys you want to use
//the second is the type of objects you store (your Object)
Hashtable <Integer,MyObject> myHashtable = new Hashtable <Integer,MyObject> ();
//Now you create your object, and set one of its fields to 4.
MyObject obj = new MyObject();
obj.setValue(4);
//You insert the object into the hashtable, with the key 0.
myHashtable.put(0,obj);
//Now if you want to change the value of an object in the hashtable, you have to retrieve it from its key, change the value by yourself then re-insert the object into the hashtable.
MyObject obj2 = myHashtable.get(0);
obj.setValue(obj.getValue() + 2);
//This will erase the previous object mapped with the key 0.
myHashtable.put(0,obj);
Hope this helps.
Upvotes: 0
Reputation: 2312
Well using a map is correct if you want to be able to quickly access your key-value pairs. If you're values are just MyObjects
with a .value()
, can't you get the object and reset that value?
MyObject myObj = treeMap.get(key);
myObj.setValue(myObj.getValue()++);
I'm using MyObject here as the poster was using Object
to denote an example type.
Upvotes: 4
Reputation: 10497
Your "object" needs to have an setter which updates the value. So you just retrieve the object in question from the map, call the setter on this object, et voila. The only obstacle you must take care of is that whatever you do in your setXXX
method does not alter the outcoming of the equals
and hashCode
methods, as this violates the invariants implied by the TreeMap
and will result in unpredictable behavior. You Object might look like this:
class AnObject {
private int cnt;
public void increment() { this.cnt++ };
}
You can pull it out of the TreeMap
, call increment()
and do not have to alter the contents of the TreeMap
itself.
Upvotes: 0