0

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
Zhro
  • 2,546
  • 2
  • 29
  • 39
  • 6
    You have to override `hashCode()` in your `SomeId` class. – Eran Dec 05 '16 at 08:53
  • 5
    You must also implement the `hashCode()` method correctly, not just the `equals()` method. See: [How does a Java HashMap handle different objects with the same hash code?](http://stackoverflow.com/questions/6493605/how-does-a-java-hashmap-handle-different-objects-with-the-same-hash-code/6493946#6493946) – Jesper Dec 05 '16 at 08:53

1 Answers1

1

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;
}
fangdi
  • 121
  • 4
  • This is my first time implementing a class used as a key. I thought I had everything covered with `Comparable`!. – Zhro Dec 05 '16 at 19:57
  • It is ok @Zhro Please always remember to implement equals and hashCode at the same time ;-) – fangdi Dec 06 '16 at 01:47