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

Time:04-29

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:

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!

CodePudding user response:

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

  • Related