record logo record

Comparable와 Comparator을 이용하여 Java 객체를 정렬할 수 있습니다.

Comparable(interface)

Comparable 구현 방법

class Info implements Comparable<Info> {
    int cost;
    int x, y;
    public Info(int c, int x, int y) {
        this.cost = c;
        this.x = x;
        this.y = y;
    }

    @Override
    public int compareTo(Info info) {
        return info.cost >= this.cost ? 1 : -1;
    }
}

@Override compareTo()

※참고※ Arrays.sort()와 Collections.sort()의 차이

Arrays.sort()

Collections.sort()

Comparator(interface)

Comparator 구현 방법

//문자열 내 마음대로 정렬하기
//https://programmers.co.kr/learn/courses/30/lessons/12915
import java.util.Arrays;
import java.util.Comparator;

class Solution {
    public String[] solution(String[] strings, int n) {
        String[] answer = new String[strings.length];
        
        Comparator<String> comparator = new Comparator<String>() {
            public int compare(String s1, String s2) {
                char c1 = s1.charAt(n);
                char c2 = s2.charAt(n);
               
                if(c1 > c2) return 1;
                else if(c1 < c2) return -1;
                else return 0;
            }
        };
        Arrays.sort(strings);
        Arrays.sort(strings, comparator);
        //...(생략)...
    }
}

References