Course contentsShow
← Java
Lesson 925 of 2,87022. Generics: Bounds and WildcardsFree lesson

Use Case: Combining Comparable and Serializable

Explore a practical example requiring a type to be both comparable and serializable for sorting and persistence.

Use Case: Combining Comparable and Serializable

What you'll learn: You'll see a practical example where a type must satisfy both Comparable and Serializable constraints—enabling objects to be sorted and saved to disk.

The Real-World Problem

Imagine you're building a leaderboard system that stores high scores. You need to:

  1. Sort scores by value (requires Comparable)
  2. Save scores to a file for persistence (requires Serializable)

A single generic method can enforce both requirements using multiple bounds.

The Solution with Multiple Bounds

import java.io.*;
import java.util.*;

public class Leaderboard {
    // T must be both Comparable (for sorting) AND Serializable (for saving)
    public <T extends Comparable<T> & Serializable> void saveTopScores(List<T> scores, String filename) throws IOException {
        Collections.sort(scores); // Uses Comparable
        
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename))) {
            out.writeObject(scores); // Uses Serializable
        }
    }
}

Why This Matters

Without multiple bounds, you'd need:

  • Two separate methods (one for sorting, one for saving)
  • Unsafe casts that could fail at runtime
  • Less reusable code across different types

By declaring <T extends Comparable<T> & Serializable>, you guarantee at compile time that any type passed to this method can be both sorted and serialized—whether it's Integer, String, or your custom Score class.

The Analogy

Think of it like hiring someone who must have both a driver's license (Comparable) and a passport (Serializable). You won't accept candidates with only one credential—you need both guarantees upfront.

Key Takeaway: Multiple bounds let you create flexible generic methods that enforce multiple capabilities simultaneously, combining features like sorting and persistence in a single, type-safe operation.