Java Notes

Comparison Overview

Comparing 3 ways - Operators, Comparable, Comparator

Comparisons are at the heart of both searching and sorting. Comparison turns out not to be quite as simple as it first appears to be. There are three ways values can be compared.

Comparing enums with == and a.compareTo(b)

enum Size {SMALL, MEDIUM, LARGE};

Unique singletons allow ==. Each enum constant, eg Size.LARGE, is an object with only one instance, sometimes referred to as a singleton. Because there is only one instance of each enum constant, the == and != operators will work as expected, and will be equivalent to .equals(), which is also legal.

Order comparison with .compareTo(). Enum constants are considered to be in the order of their declaration. In the example above, Size.Medium is greater than Size.SMALL.

   Size mySize;
   Size rackSize;
   String response;
   . . .
   if (rackSize == mySize) {
       response = "I'll buy it";
   } else if (mySize.compareTo(rackSize) > 0) {
       response = "Do you have something larger.";
   } else {
       response = "Too big.";
   }