[Java] Comparable / Comparator

Dawon Seo·2024년 3월 21일
0

Comparable

  • 인터페이스로, 구현체가 필요하다.
  • lang 패키지 안에 있어 import할 필요가 없다
  • compareTo(T o) 메소드 재정의가 필요
  • 자기 자신과 매개변수 객체를 비교
class Student implements Comparable<Student> {
	int age;
    int classNumber;
    
    Student(int age, int classNumber) {
    	this.age = age;
        this.classNumber = classNumber;
    }
    
    @Override
    public int compareTo(Student o) {
    	// 자기자신의 age가 o의 age보다 크다면 양수
    	if (this.age > o.age) {
        	return 1;
        }
        // 자기자신의 age가 o의 age와 같다면 0
        else if(this.age == o.age) {
        	return 0;
        }
        // 자기자신의 age가 o의 age보다 작다면 음수
        else {
        	return -1;
        }
       
    }
}

위의 코드는 아래와 같다.

class Student implements Comparable<Student> {
	int age;
    int classNumber;
    
    Student(int age, int classNumber) {
    	this.age = age;
        this.classNumber = classNumber;
    }
    
    @Override
    public int compareTo(Student o) {
    	// age를 비교하여 자신이 더 크면 양수, 같으면 0, 작으면 음수를 반환한다.
    	return this.age - o.age;
    }
}

자료형의 범위를 넘는 경우를 주의해야 한다. (오버플로우와 언더플로우)

Comparator

  • 인터페이스로, 구현체가 필요하다.
  • util 패키지에 있어 import가 필요
  • 실질적으로 compare(T 01, T 02)만 구현하면 된다.
  • 두 매개변수 객체를 비교
import java.util.Comparator;
class Student implements Comparator<Student> {
	int age;
    int classNumber;
    
    Student(int age, int classNumber) {
    	this.age = age;
        this.classNumber = classNumber;
    }
    
    @Override
    public int compare(Student o1, Student o2) {
    	// o1의 학급이 o2의 학급보다 크다면 양수
		if(o1.classNumber > o2.classNumber) {
			return 1;
		}
		// o1의 학급이 o2의 학급과 같다면 0
		else if(o1.classNumber == o2.classNumber) {
			return 0;
		}
		// o1의 학급이 o2의 학급보다 작다면 음수
		else {
			return -1;
		}
    }
}

위 코드는 아래와 같다.

import java.util.Comparator;
class Student implements Comparator<Student> {
	int age;
    int classNumber;
    
    Student(int age, int classNumber) {
    	this.age = age;
        this.classNumber = classNumber;
    }
    
    @Override
    public int compare(Student o1, Student o2) {
    	return o1.classNumber - o2.classNumber;
    }
}

0개의 댓글