Results 1 to 3 of 3
Thread: Strange HashMap behavior
- 08-24-2011, 06:45 PM #1
Member
- Join Date
- Dec 2007
- Posts
- 6
- Rep Power
- 0
Strange HashMap behavior
Hi all,
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:
Basically, I expect to see two "Yes!"s, indeed, it prints only one. I did a thorough debugging and realized that the reference number for myHashSet doesn't change after removing one of it's members. So, there should be no reason for this program not to print the second "Yes!".Java Code: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 06:49 PM.
- 08-24-2011, 07: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, 08: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=406697253
hc=406697253
Yes1!
hc=406600899 <<<<< after remove
hc=406697253 <<<<< after added back
Similar Threads
-
Strange behaviour
By imadabh in forum Threads and SynchronizationReplies: 1Last Post: 05-11-2011, 03:31 PM -
Strange JVM behaviour
By pjpr in forum Advanced JavaReplies: 13Last Post: 01-03-2011, 07:39 PM -
Strange behaviour in serialization
By Wolverine in forum NetworkingReplies: 0Last Post: 05-23-2009, 12:03 PM -
AffinedTransform strange behaviour
By Echilon in forum AWT / SwingReplies: 3Last Post: 12-11-2008, 09:58 AM -
Strange behaviour in swing
By cbalu in forum AWT / SwingReplies: 1Last Post: 05-23-2008, 09:23 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks