Comparable 인터페이스
클래스에 자연스러운 순서를 부여하도록 Comparable을 구현하고 Collections.sort와 함께 사용합니다.
Comparable 인터페이스은(는) CoddyKit의 무료 Java Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Java Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
비교 가능 인터페이스
Comparable<T>은 클래스에 자연 순서를 부여합니다. 이를 구현하면 Collections.sort(), Arrays.sort(), TreeSet과 같은 정렬 컬렉션을 사용해 인스턴스를 정렬할 수 있습니다.
비교 가능 인터페이스 구현
compareTo(T other)를 구현하여 음수(this < other), 0(같음), 양수(this > other)를 반환하도록 하십시오.
class Product implements Comparable<Product> {
private final String name;
private final double price;
Product(String name, double price) {
this.name = name; this.price = price;
}
@Override
public int compareTo(Product other) {
return Double.compare(this.price, other.price); // ascending by price
}
@Override public String toString() { return name + "($" + price + ")"; }
}
List<Product> products = new ArrayList<>(List.of(
new Product("Mouse", 29.99),
new Product("Laptop", 999.0),
new Product("Keyboard", 79.99)
));
Collections.sort(products);
System.out.println(products); // [Mouse($29.99), Keyboard($79.99), Laptop($999.0)]compareTo 계약
비교 가능 인터페이스를 올바르게 구현하려면 다음 계약을 지켜야 합니다.
- 반대칭성: sgn(a.compareTo(b)) == -sgn(b.compareTo(a))
- 추이성: a > b이고 b > c이면 a > c입니다.
- 일관성: a.compareTo(b) == 0이면 a.equals(b)가 성립하도록 하는 것이 강력히 권장됩니다.
기본 타입을 안전하게 비교하기
compareTo에서 기본 타입을 절대 빼지 마십시오. 정수 오버플로로 인해 잘못된 결과가 나올 수 있습니다. Integer.compare(), Double.compare() 등을 사용하십시오.
// WRONG: integer subtraction can overflow
int compareTo(Player other) {
return this.score - other.score; // overflow if scores differ by > Integer.MAX_VALUE
}
// CORRECT: use Integer.compare
int compareTo(Player other) {
return Integer.compare(this.score, other.score);
}
// For strings: delegate to String.compareTo
int compareTo(Player other) {
return this.name.compareTo(other.name); // String handles it correctly
}TreeSet의 자연 순서
비교 가능 인터페이스를 구현한 클래스는 TreeSet과 TreeMap 같은 정렬 컬렉션에 자동으로 정렬되어 들어갑니다.
class Priority implements Comparable<Priority> {
enum Level { LOW, MEDIUM, HIGH, CRITICAL }
final Level level;
final String task;
Priority(Level level, String task) { this.level = level; this.task = task; }
@Override
public int compareTo(Priority other) {
return this.level.compareTo(other.level); // enum ordinal order
}
@Override public String toString() { return level + ": " + task; }
}
TreeSet<Priority> queue = new TreeSet<>();
queue.add(new Priority(Priority.Level.CRITICAL, "Fix prod crash"));
queue.add(new Priority(Priority.Level.LOW, "Update docs"));
queue.add(new Priority(Priority.Level.HIGH, "Deploy feature"));
queue.forEach(System.out::println);
// LOW: Update docs
// HIGH: Deploy feature
// CRITICAL: Fix prod crash여러 필드의 비교 가능 인터페이스
여러 필드로 정렬하려면 비교를 연결하십시오. 첫 번째 기준으로 정렬한 뒤, 첫 번째 기준이 같을 때 두 번째 기준을 적용합니다.
class Employee implements Comparable<Employee> {
final String dept, name;
final double salary;
Employee(String dept, String name, double salary) {
this.dept = dept; this.name = name; this.salary = salary;
}
@Override
public int compareTo(Employee other) {
int deptCmp = this.dept.compareTo(other.dept);
if (deptCmp != 0) return deptCmp; // primary: by dept
return this.name.compareTo(other.name); // secondary: by name
}
}비교 가능 인터페이스와 equals의 일관성
a.compareTo(b) == 0일 때 그리고 그럴 때만 a.equals(b)가 성립하도록 하는 것이 강력히 권장되지만 필수는 아닙니다. 이를 위반하면 정렬된 집합과 맵에서 찾기 어려운 버그가 발생합니다.
// BigDecimal violates this: new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) == 0
// but new BigDecimal("2.0").equals(new BigDecimal("2.00")) == false
// This causes TreeSet to treat them as equal (only one stored)
TreeSet<java.math.BigDecimal> set = new TreeSet<>();
set.add(new java.math.BigDecimal("2.0"));
set.add(new java.math.BigDecimal("2.00"));
System.out.println(set.size()); // 1 — compareTo-equal → same elementCollections.sort로 정렬하기
Collections.sort()와 Arrays.sort()는 비교 가능 인터페이스가 정의한 자연 순서를 사용합니다.
List<String> names = new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
Collections.sort(names); // natural alphabetical order
System.out.println(names); // [Alice, Bob, Charlie]
String[] arr = {"banana", "apple", "cherry"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [apple, banana, cherry]
// Stream sorted() uses natural order
names.stream().sorted().forEach(System.out::println);이진 검색에서의 비교 가능 인터페이스
Collections.binarySearch()를 사용하려면 리스트가 자연 순서로 정렬되어 있어야 하며 요소가 비교 가능 인터페이스를 구현해야 합니다.
List<Integer> sorted = new ArrayList<>(List.of(1, 3, 5, 7, 9, 11));
int idx = Collections.binarySearch(sorted, 7);
System.out.println("Found 7 at index: " + idx); // 3
int missing = Collections.binarySearch(sorted, 4);
System.out.println("4 not found, insertion point: " + (-missing - 1)); // 2비교 가능 인터페이스와 Comparator 비교
주요 차이점:
- 비교 가능 인터페이스: 클래스 자체의 자연 순서를 정의하며, 클래스마다 하나만 존재합니다.
- Comparator: 외부 정렬 순서를 정의하며, 여러 개를 만들고 조합할 수 있습니다.
실전: Leaderboard
비교 가능 인터페이스를 사용해 점수가 높은 순서로 자연 정렬하는 Leaderboard입니다.
class LeaderboardEntry implements Comparable<LeaderboardEntry> {
final String player;
final int score;
final long timestamp;
LeaderboardEntry(String player, int score) {
this.player = player; this.score = score;
this.timestamp = System.nanoTime();
}
@Override
public int compareTo(LeaderboardEntry other) {
int scoreCmp = Integer.compare(other.score, this.score); // descending
if (scoreCmp != 0) return scoreCmp;
return Long.compare(this.timestamp, other.timestamp); // earlier = higher
}
@Override public String toString() { return player + ": " + score; }
}
TreeSet<LeaderboardEntry> board = new TreeSet<>();
board.add(new LeaderboardEntry("Alice", 950));
board.add(new LeaderboardEntry("Bob", 1200));
board.add(new LeaderboardEntry("Carol", 950));
board.forEach(System.out::println);
// Bob: 1200 / Alice: 950 / Carol: 950빠른 확인
현재 객체가 인수보다 작을 때 compareTo()는 무엇을 반환합니까?
복습: 비교 가능 인터페이스
핵심 내용:
- 비교 가능 인터페이스를 구현하여 클래스의 자연 순서를 정의합니다.
- compareTo는 음수(작음), 0(같음), 양수(큼)를 반환합니다.
- Integer.compare()/Double.compare()를 사용하고, 오버플로 위험이 있으므로 절대 빼지 마십시오.
- 여러 필드를 정렬할 때는 비교를 연결합니다. 첫 번째 기준 → 두 번째 기준 순서입니다.
- 자연 순서는 Collections.sort, Arrays.sort, TreeSet, TreeMap에서 사용됩니다.
- 비교 가능 인터페이스는 ONE개의 순서를 정의하며, 여러 순서가 필요하면 Comparator를 사용합니다.
자주 묻는 질문
“Comparable 인터페이스” 강의는 무료인가요?
네 — “Comparable 인터페이스” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Java Academy 강의 전체를 잠금 해제할 수 있습니다. Java Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“Comparable 인터페이스”에서 뭘 배우나요?
클래스에 자연스러운 순서를 부여하도록 Comparable을 구현하고 Collections.sort와 함께 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 Java Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Java Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Java Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Comparable 인터페이스” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Java Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Java Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Comparable 인터페이스
- Comparator와 람다 정렬
- thenComparing을 사용한 다중 키 정렬
- 배열과 컬렉션 정렬 실습