Step-by-Step

[인터페이스] Comparable & Comparator 본문

언어/JAVA

[인터페이스] Comparable & Comparator

희주(KHJ) 2021. 8. 11. 21:04

Comparable은 Java.lang 패키지에, Comparator은 Java.util 패키지에 있는 인터페이스이다

 

Comparable

정렬 수행시 기본적으로 적용되는 정렬 기준이 되는 메서드를 정의해 놓는 인터페이스

자바에서 제공되는 정렬이 가능한 클래스들은 모두 Comparable 인터페이스를 구현하고 있으며

정렬시에 Comparable의 구현 내용에 맞춰 정렬이 수행된다

기본적인 메서드 구성은 아래와 같다

int compareTo(T o){
	...
}

클래스 내에서 구현할 때는 Comparable을 먼저 상속한 후, Override를 통해 구현한다

import java.lang.Comparable;
class Student implements Comparable<Student>{
	String StudentName;
    int StudentId;
    
    //기본 생성자
    public Student(String StudentName, int StudentId){
    	this.StudentName = StudentName;
        this.StudentId = StudentId;
    }
    
	@Override
	public int compareTo(Student st) {
		return Integer.compare(StudentId, st.StudentId);
	}
}

https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#method.summary

 

Comparable (Java Platform SE 8 )

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. Lists (and arrays) of o

docs.oracle.com

 

Comparator

Comparable의 기본 정렬 기준과는 다른 방식으로 정렬하고 싶을 때 사용하는 클래스

Comparable에서는 자기 자신(객체)과 다른 객체를 비교하는 compareTo를 사용했다면,

Comparator에서는 서로 다른 두 객체를 비교하는 compare가 기본 메소드로 정의된다

int compare(T o1, T o2){
	...
}

마찬가지로 Comparator 객체를 먼저 상속한 후, compare을 Override하여 사용한다

import java.lang.Comparator;
class Student implements Comparator<Student>{
	String StudentName;
    int StudentId;
    
    //기본 생성자
    public Student(String StudentName, int StudentId){
    	this.StudentName = StudentName;
        this.StudentId = StudentId;
    }
    
	@Override
	public int compare(Student st1, Student st2) {
		return Integer.compare(st1.StudentId, st2.StudentId);
	}
}

Comparable에서는 기존 객체의 StudentId와 매개변수로 들어온 객체의 StudentId를 비교하여 return하였다면,

Comparator에서는 매개변수로 들어온 두 객체의 StudentId를 비교하여 return하게 된다

https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#method.summary

 

Comparator (Java Platform SE 8 )

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. In the foregoing description, the notation sgn(expression) designates the mathematical s

docs.oracle.com

 

[참조]

https://st-lab.tistory.com/243

Comments