JAVA - 객체 간 정렬 ( Comparable<T> , Comparator<T> )

TopOfTheHead·2025년 9월 26일

자바 ( JAVA )

목록 보기
15/23

특정 Class의 객체를 정렬하기 위한 용도로 활용되는 Interface
Comparable<T> , Comparator<T>
。해당 두 interface는 정렬목적으로 비교기준으로서 활용되는 방식은 동일하지만 사용방식과 적용위치가 다르다.

Comparable<T> :
。자기 자신과 동일 Class type을 가지는 instance 간 비교용도의 Interface

단일 Field를 기반으로 한 정렬기준이 필요할 경우 정렬기준이 되는 Class에 직접 상속하여 활용
다양한 Field를 기준으로 한 복수의 정렬기준이 필요한 경우 각각의 Comparator<T>를 생성하여 정의

public interface Comparable
{
	int CompareTo(T o);
}

int compareTo(T o) : Comparable<T>의 구현 method로서 객체 자신(this)와 다른객체(o)간 비교를 수행

Class의 특정 field를 기반으로 instance를 구성하는 Class[] 배열의 정렬 시 사전에 Class에 상속하여 정의해야함
▶ 정의된 경우 Collections.sort(List<Class>객체) 또는 Arrays.sort(Class[]객체)를 통해 배열을 구성하는 Class instance를 정렬

。정렬을 수행할 instance가 속하는 Class에 해당 interfacemethod를 상속 및 구현

Natural Ordering을 정의 시 사용한다.

  • 구현 예시
class Person implements Comparable<Person>{
    String name;
    int age;
    public Person(String name, int age){
        this.age = age;
        this.name = name;
    }
    public int compareTo(Person o){
        return this.age - o.age; // 구현의 기준이 될 field
    }
}
class Main{
    public static void main(String[] args) {
        Person[] pg = new Person[]{
            new Person("lee",26),
            new Person("lee",24),
            new Person("lee",28),
        };
        Arrays.sort(pg);
        for(Person p : pg){
            System.out.print(p.age+" ");
        }
    }
}

결과값 : 24 26 28

Comparable<클래스>를 구현하는 경우 Arrays.sort(클래스객체)를 통해 Class의 특정 field를 기준으로 정렬이 가능

compareTo(T o) Method의 정렬방식
。배열을 구성하는 instance 간 자신(this)과 다른 객체(o)간 비교를 수행하면서 배열정렬을 수행

  • 정수 field의 정렬 시
public int compareTo(Person o){
        return this.age - o.age; // 구현의 기준이 될 field
    }

compareTo metod에서 this < o면 음수 , this = o면 0 , this > o면 양수반환

this.age - o.age < 0 : 정렬 상 this 객체가 작으므로 앞에 와야함.
this.age - o.age == 0 : 정렬 상 순서 유지
this.age - o.age > 0 : 정렬 상 this 객체가 크므로 뒤에 와야함.
return - ( this.age - o.age );로 설정 시 내림차순으로 정렬 수행

  • 문자열 field의 정렬 시
public int compareTo(Person o){
        return this.name.compareTo(o.name); // 구현의 기준이 될 field
    }

return this.문자열변수.CompareTo(o.문자열변수)으로 정의하는 경우 문자열field의 오름차순으로 정렬 수행
return - this.name.compareTo(o.name);로 설정 시 내림차순으로 정렬 수행

Comparator<T>
。동일 Class type을 가지는 instance 간 비교 용도의 Interface
Comparator<T> c로 변수 선언 시 c.compare(T객체1,T객체2)를 통해 비교가능.

Comparable<T>와 달리 정렬할 Class에 직접 선언하지 않고, Comparator 역할의 Class에 상속하여 필요할때 호출하여 활용
다양한 Field를 기반으로한 정렬기준이 필요할 경우 외부에서 각각 선언하여 활용

Comparator<? super T> :
T 또는 해당 상위타입을 비교할 수 있는 Comparator

public interface Comparator<T> {
    int compare(T o1, T o2);
}

int compare(T o1, T o2) : Comparator<T>의 구현 method로서 동일 Class의 객체(o1)와 객체(o2)간 비교를 수행

。객체 간 비교 기준이 없을때 유용하게 사용.
▶ 정렬 or 우선순위큐에서 사용되는 방식

class NameComparator implements Comparator<Person>{
    public int compare(Person p1, Person p2){
        return p1.name.compareTo(p2.name);
    }
}

Comparator<T>int compare(T o1, T o2) 상속 및 구현하여 Comparator Class 생성
Collections.sort(List<Class>객체, Comparator객체) 또는 Arrays.sort(Class[]객체, Comparator객체)를 통해 배열을 구성하는 Class instance를 정렬


구현 예시

class Person {
    String name;
    int age;
    public Person(String name, int age){
        this.age = age;
        this.name = name;
    }
}
// Person[]를 name field 기반 정렬 시 활용
class NameComparator implements Comparator<Person>{
    public int compare(Person p1, Person p2){
        return p1.name.compareTo(p2.name);
    }
}
// Person[]를 age field 기반 정렬 시 활용
class AgeComparator implements Comparator<Person>{
    public int compare(Person p1, Person p2){
        return p1.age - p2.age;
    }
}
class Main{
    public static void main(String[] args) {
        Person[] pg = new Person[]{
            new Person("lee",26),
            new Person("kim",24),
            new Person("go",28),
        };
        Arrays.sort(pg, new NameComparator());
        for(Person p : pg){
            System.out.print(p.name+" ");
        }
        Arrays.sort(pg, new AgeComparator());
        for(Person p : pg){
            System.out.print(p.age+" ");
        }
    }
}

결과값 : go kim lee 24 26 28
。특정 Comparator Classcompare method에 에 구현된 특정 field을 기준으로 정렬을 수행.
Person Classagename field에 따른 각각의 Comparator를 생성 후 각각의 field에 대한 정렬을 수행가능.

ex ) Arrays.sort(pg, new NameComparator()); : 배열을 name field 기준으로 정렬 수행.

compare(T o1, T o2) Method의 정렬방식
。동일 Class Type의 배열을 구성하는 instance의 객체(o1, o2)간 비교를 수행하면서 배열정렬을 수행

  • 정수 field의 정렬 시
public int compare(T o1, T o2){
        return o1.age - o2.age;
    }

compare metod에서 o1 < o2면 음수 , o1 = o2면 0 , o1 > o2면 양수반환

o1.age - o2.age < 0 : 정렬 상 o1 객체가 작으므로 앞에 와야함.
o1.age - o2.age == 0 : 정렬 상 순서 유지
o1.age - o2.age > 0 : 정렬 상 o1 객체가 크므로 뒤에 와야함.
return - ( o1.age - o2.age );로 설정 시 내림차순으로 정렬 수행

  • 문자열 field의 정렬 시
public int compare(T o1, T o2){
        return o1.name.compareTo(o2.name);
    }

return o1.문자열변수.CompareTo(o2.문자열변수)으로 정의하는 경우 문자열field의 오름차순으로 정렬 수행
return - o1.name.compareTo(o2.name);로 설정 시 내림차순으로 정렬 수행

profile
공부기록 블로그

0개의 댓글