Hi,
I want to replace a HashMap key with another value. e.g. I have a HashMap as:
{AA: aa, BB:bb, CC:cc}. Now, I want something like, {AA: aa, DD:bb, CC:cc}. So, I have replace BB by DD.
Please help me with finding a solution!
Thanks,
Pompeez
Printable View
Hi,
I want to replace a HashMap key with another value. e.g. I have a HashMap as:
{AA: aa, BB:bb, CC:cc}. Now, I want something like, {AA: aa, DD:bb, CC:cc}. So, I have replace BB by DD.
Please help me with finding a solution!
Thanks,
Pompeez
Unless I were to write my own method extending a HashMap, I would
myHashMap.remove(BB);
then
myHashMap.put( DD, bb);
Thanks a lot for your reply. I need a little more clarification plz!!
Suppose I have a hashmap like this - {AA: aa, BB:bb, CC: {FF: ff, BB: xx}}. Now, I need to replace BB by DD in BB:bb. Given this, if I remove BB:bb, and add DD:bb, how can I make sure this new pair will get added in the exact place of BB:bb, and not within CC?
Thanks!
pompeez
The value of the hash key, and its result when using your hash function, will determine where within the structure your value will be placed and retrieved from. The same key for two pairs (if, in using your Map, you are permitting two or more occurrences of the same key, something a Map does not usually allow) will result in a value being in the same location ... then the separation of the values depends on your collision resolution scheme.
The result of the hash function for BB and DD as inputs would have to be the same for the values associated with these keys to be in the "same location". But ... why does it matter to you that they are in the same location? A HashMap does not create a sequence in the same way a linked list or an array creates a sequence, with elements in a set order and being addressed in that set order. The "Hash" part of the HashMap structure allows you to FIND the value quickly, using only the key. The result of the hash function given the key input tells you where to look for the value in your structure. You don't walk sequentially, you don't guess in the structure and then guess again, you "know" because of the result of the hash function. The only "order" to the user is the order within some sequence structure in which you store references to keys or in which you find values, not within the HashMap itself.
There is no reason that a second HashMap cannot be the "value" part of a pair in the first HashMap, and the second BB would be placed in the second HashMap according to the hash result for that structure. However, the values must be the same kind of objects, and a HashMap is a very different object than a string ... so unless you are setting values as being members of class Object (requiring you to do a whole lot of typechecking and casting) you are going to have some issues with your structure is you are going to have a HashMap value.