알고리즘/알고리즘 개념

[알고리즘 개념] 객체 정렬하기

잔디🌿 2025. 2. 23. 16:04

가끔 알고리즘을 풀다보면 객체를 특정 인자를 기준으로 정렬해야할 때가 온다.

그럴 때는 해당 객체 클래스에서 Comparable<T> 인터페이스를 구현하면 된다

 

class Student implements Comparable<Student> {
    int kor, eng, math;

    public Student(int kor, int eng, int math){
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }

    @Override
    public int compareTo(Student student) { // 국어 점수 기준 오름차순 정렬
        return this.kor - student.kor;
    }
};

오름차순 기준으로

comparerTo를 Override하고 이 속에서 해당 클래스의 값 - 파라미터로 들어온 값을 하면 된다.

 

만약 내림차순을 하고싶다면 그 반대로 하면 된다!