
Comparable 인터페이스를 구현하지 않은 클래스의 객체가 들어있는 목록을 정렬하려면, Comparable 인터페이스를 구현하거나 Comparator 인터페이스를 구현한 객체를 CollectionModify::sort 메서드의 comparator 매개변수로 전달해야 합니다.
예를 들어, String 클래스는 Comparable 인터페이스를 구현했기 때문에 정렬이 가능합니다. 하지만, 다른 클래스의 객체가 들어있는 목록을 정렬하려면 Comparator 인터페이스를 구현한 객체를 사용해야 합니다.
다음은 예시입니다.
#hostingforum.kr
java
// Comparable 인터페이스를 구현한 클래스
class Person implements Comparable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return this.age - other.age;
}
}
// Comparable 인터페이스를 구현하지 않은 클래스
class Book {
private String title;
private int price;
public Book(String title, int price) {
this.title = title;
this.price = price;
}
}
public class Main {
public static void main(String[] args) {
List personList = new ArrayList<>();
personList.add(new Person("John", 25));
personList.add(new Person("Alice", 30));
personList.sort(Comparator.naturalOrder()); // Comparable 인터페이스를 구현한 클래스의 객체를 정렬
List bookList = new ArrayList<>();
bookList.add(new Book("Java Programming", 20));
bookList.add(new Book("Python Programming", 30));
bookList.sort(Comparator.comparingInt(Book::getPrice)); // Comparable 인터페이스를 구현하지 않은 클래스의 객체를 정렬
}
}
위 예시에서, Person 클래스는 Comparable 인터페이스를 구현했기 때문에 naturalOrder() comparator를 사용하여 정렬이 가능합니다. 하지만, Book 클래스는 Comparable 인터페이스를 구현하지 않았기 때문에 Comparator 인터페이스를 구현한 객체를 사용하여 정렬이 가능합니다.
2025-04-20 03:37