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!");
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!”.
Any kind of help is really appreciated.
Hashmap keys off the hash/equals of the key (which has been pointed out, is changing). If you care about identity, you should use an java.util.IdentityHashMap