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.- Comparison operators (
< <= == != >= >
) for primitive values.if (a < b) ...
- Implementing the
Comparable
interface requires defining acompare()
method. Java classes that have a natural sorting order (eg,String
) often implement Comparable. That Comparable is implemented as an instance method of the class that is being compared (in contrast to Comparator).if (s.compareTo(t) < 0) ...
- Implementing the
Comparator
interface requires defining a thecompare()
method. This method is not defined in the classes that are being compared, but usually in a small utility class which only defines this method. Comparators are very useful for classes that can be sorted in multiple ways.if (comparator.compare(x, y) < 0) ...
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."; }