Search code examples
javadictionarycomparable

Why can I not get() from this map with a copy of my object?


I have an object which has an id of type UUID. It is equal to another object if this UUID matches. I can confirm that I'm implemented equals() and compareTo() correctly and each provide an @Override for the Comparable interface.

Why then am I getting null when I query for my object with a copy of the id?

public class SomeId implements Comparable<SomeId> {
UUID id;

SomeId(
   UUID id)
{
   this.id = id;
}

UUID getUniqueId() {
   return id;
}

@Override
public String toString() {
   return id.toString();
}

@Override
public boolean equals(
   Object obj)
{
   if (this == obj)
      return true;

   if (obj == null)
      return false;

   if (getClass() != obj.getClass())
      return false;

   SomeId o = (SomeId)obj;

   boolean b = id.equals(o.getUniqueId());

   return b;
}

@Override
public int compareTo(
   SomeId val)
{
   return id.compareTo(val.getUniqueId());
}
}

Main:

Map<SomeId, Integer> map = new HashMap<>();

SomeId id1 = new SomeId(UUID.randomUUID());
SomeId id2 = new SomeId(UUID.fromString(id1.toString()));

if (id1.equals(id2))
  System.out.println("Equal!");

if (id1.compareTo(id2) == 0)
  System.out.println("Equal!");

System.out.println(id1);
System.out.println(id2);

map.put(id1, new Integer(1));

System.out.println(map.get(id1));

// Always retrns null?
System.out.println(map.get(id2));

When running this program I get the following output:

Equal!
Equal!
f9b9b419-659e-4da7-9043-e7e51bef7bad
f9b9b419-659e-4da7-9043-e7e51bef7bad
1
null

Solution

  • Please implement hashCode ;-)

    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final Object $id = this.id;
        result = result * PRIME + ($id == null ? 43 : $id.hashCode());
        return result;
    }