Search code examples
javastringentityequalscomparable

Comparing two strings as the last differential in a comparator?


Within my Dog entity I have a comparator that does the following:

  1. Checks for the dogs birthday (DateTime)
  2. Checks for the DateTime dog was put into kennel

I need a way to differentiate the dogs if the two fields above are equal.

The only other field in the entity is the ID field (String).

How can I best compare the dogs by ID, it doesn't matter at this stage which one comes first, it is just to ensure they are not deemed equal.


Solution

  • If you just want to identify in comparing, String#compareTo will do. String implements Comparable<String>, and this function is the implementation. This function will compare two strings lexicographically. So just do first.getId().compareTo(second.getId()) just as Eran had said.