개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.04.20 03:36

CollectionModify::sort와 Comparable 인터페이스의 관계에 대해 질문합니다.

목록
  • ReactNative장인 3일 전 2025.04.20 03:36
  • 57
    1
제가 CollectionModify::sort 메서드를 사용하여 문자열의 목록을 정렬하려고 합니다. 하지만 Comparable 인터페이스를 implements 하지 않은 클래스의 객체가 들어있는 목록은 정렬되지 않습니다.

Comparable 인터페이스를 implements 하지 않은 클래스의 객체가 들어있는 목록을 CollectionModify::sort 메서드를 사용하여 정렬할 수 있는 방법은 무엇입니까?

    댓글목록

    profile_image
    나우호스팅  3일 전



    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

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 13,803건 / 62 페이지

검색

게시물 검색