Course contentsShow
← Java
Lesson 1317 of 2,87030. Comparable and ComparatorFree lesson

Comparing Primitive Wrapper Classes

Wrapper classes like Integer, Double, and String implement Comparable and define natural numeric or lexicographic ordering.

Comparing Primitive Wrapper Classes

What you'll learn: How Java's wrapper classes like Integer, Double, and String provide built-in natural ordering without extra work.

The Built-In Natural Order

You've already seen how to implement Comparable in your custom classes, but the good news is that Java's primitive wrapper classes already do this for you. Classes like Integer, Double, Float, Long, Character, Byte, Short, and Boolean all implement Comparable<T> with sensible default ordering.

For numeric wrappers (Integer, Double, etc.), the natural order is numeric ordering — smaller numbers come before larger ones. For String, it's lexicographic ordering (dictionary order, based on Unicode values). For Boolean, false comes before true.

Why This Matters

When you sort a List<Integer> using Collections.sort() or add elements to a TreeSet<Double>, Java automatically uses the wrapper class's built-in compareTo method. You don't need to write a custom comparator or implement anything yourself.

Example scenario:

List<Integer> numbers = new ArrayList<>(Arrays.asList(42, 7, 99, 15));
Collections.sort(numbers);
// Result: [7, 15, 42, 99] - sorted numerically
TreeSet<String> words = new TreeSet<>();
words.add("Zebra");
words.add("Apple");
words.add("Mango");
// TreeSet maintains order: [Apple, Mango, Zebra]

Consistent with equals

These wrapper classes follow the rule that compareTo is consistent with equals: if a.compareTo(b) == 0, then a.equals(b) is true. This ensures predictable behavior in sorted collections.

Key Takeaway: Wrapper classes like Integer, Double, and String implement Comparable with natural numeric or lexicographic ordering, allowing them to be sorted and used in sorted collections automatically.