1

I have a HashMap<Ist, Ist> registro = new HashMap<Ist, Ist>()

I need to find the key of certain values, for which im using this method I found

 public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
    for (Map.Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

I do registro.put(origenCopia, istOrigen)

However getKeyByValue(this.registro, istDestino) returns null, I'm guessing it's because istDestino and istOrigen aren't the exact same objects, but their contents are.

Abrelaboca
  • 27
  • 1
  • 4

1 Answers1

2

This seems to be because you didn't implement /override the default .equals() and .hashCode() methods for your Ist class.

If you are using an IDE to develop, you can (in 99% of the cases) have them automatically generated. A quick google search related on how to achieve this in your IDE should help.

Basically you need to implement these 2 methods in order to tell the JVM how you want to compare the objects. This basically means which attributes have to be equal.

Unless you implement the aforementioned methods, your objects will be equal only if they are indeed one and the same object (regardless if they have identical attributes or not).

Syn
  • 776
  • 12
  • 30