Results 1 to 3 of 3
Thread: Strange HashMap behavior
- 08-24-2011, 07:45 PM #1Member
- Join Date
- Dec 2007
- Rep Power
Strange HashMap behavior
In my program, I have a HashMap. It has HashSets of Strings as its keys and PriorityQueues of Strings as its values. When I change the content of one of its keys, it is no longer remain as a member of the HashMap. This seems strange to me, since I do not change the reference of the key. I just change its content. Please take a look at the following snippet:
HashMap<HashSet<String>, PriorityQueue<String>> myHashMap=new HashMap<>(); HashSet<String> myHashSet=new HashSet<>(); myHashSet.add("abc"); myHashSet.add("mnq"); myHashSet.add("al;ksghl"); PriorityQueue<String> myPriorityQueue=new PriorityQueue<>(); myPriorityQueue.add("3h4"); myPriorityQueue.add("lskdjf"); myHashMap.put(myHashSet, myPriorityQueue); if(myHashMap.containsKey(myHashSet)) System.out.println("Yes!"); myHashSet.remove("abc"); if(myHashMap.containsKey(myHashSet)) System.out.println("Yes!");
Any kind of help is really appreciated.
Last edited by mjdousti; 08-24-2011 at 07:49 PM.
- 08-24-2011, 08:59 PM #2
If you change the value of a key, won't that be a problem? The HashMap uses the hash of the key's content to position the value. If you want to change a the value of a key, perhaps you should remove it, change it and put it back.
- 08-24-2011, 09:41 PM #3
For more information: print out the hashCode for myHashSet after it has been added to the HashMap,
then again after the remove call.
Then add back the item removed and print the hashcode again.
Here is what I see:
hc=406600899 <<<<< after remove
hc=406697253 <<<<< after added back
- By imadabh in forum Threads and SynchronizationReplies: 1Last Post: 05-11-2011, 04:31 PM
- By pjpr in forum Advanced JavaReplies: 13Last Post: 01-03-2011, 08:39 PM
- By Wolverine in forum NetworkingReplies: 0Last Post: 05-23-2009, 01:03 PM
- By Echilon in forum AWT / SwingReplies: 3Last Post: 12-11-2008, 10:58 AM
- By cbalu in forum AWT / SwingReplies: 1Last Post: 05-23-2008, 10:23 PM