1

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!

nsh
  • 15
  • 1
  • 5

1 Answers1

1

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

Itisdud
  • 41
  • 7
  • You need to be careful with a mutable list as a key, as explains here: https://stackoverflow.com/questions/42182116/java-using-hashmap-with-list-as-key – Ricky Lim Apr 28 '22 at 10:56
  • @RickyLim `IdentityHashMap` avoids the problem of a mutable class as a key, since `System.identityHashCode()` is used for keying and won't change. – Kayaman Apr 28 '22 at 11:02
  • Is there such thing also for a List? I mean to find an item in a list with `list.contains()` which searches for the item with its reference. – nsh Apr 28 '22 at 12:40