Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get an element from a hashmap by == operator, rather than .equal in java

I have a hashmap and I want to find a key by reference. I found out that the get(key) method uses .equal() to find a key. But I need it to use == to find it by reference.
For example in the below code:

HashMap<List, String> myMap = new HashMap<List, String>();
List<String> pets = new ArrayList<>();
pets.add("cat");
pets.add("dog");
    
myMap.put(pets, "pets");
    
List<String> animals = new ArrayList<>();
animals.add("cat");
animals.add("dog");
    
var alreadyExists = myMap.containsKey(animals); //I want this to return false
if(!alreadyExists) {
    myMap.put(animals, "pets");
}
    
System.out.println(myMap.size());  //and therefore, I want this to print 2!

As I have commented, I need the alreadyExists to be false.

I am new to java but in c# you could easily do such things with something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var alreadyExists = myMap.containsKey(a => a == animals);

Is there any way to do such things in Java, as I do not want to override the equal() method!

>Solution :

Java has a class called IdentityHashMap, which does exactly what you want – it compares the reference rather than using equals().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading