2023-java-study / book-study

북 스터디 기록 레포지토리
0 stars 0 forks source link

[Item 14] 열거타입의 Comparable 구현 #44

Closed gmelon closed 1 year ago

gmelon commented 1 year ago

p.87 에서 열거타입이 Comparable을 구현했다는게 무슨 의미인지 궁금합니다. 열거타입의 필드를 자동으로 비교에 사용하는걸까요?

ssstopeun commented 1 year ago

enum의 경우 열거된 순서에 따라 compareTo로 비교할 수 있습니다.

public enum Week {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

public class EnumTest {
    public static void main(String[] args) {

        System.out.println(Week.MONDAY.compareTo(Week.SUNDAY));
        System.out.println(Week.SATURDAY.compareTo(Week.WEDNESDAY));
    }
}

image

코드를 실행했을 때 아래와 같이 순서를 알 수 있게 되는데요. 순서가 명확한 값 클래스를 작성한다면 comparable인터페이스를 구현하자는 말이 핵심인 것 같아요. enum또한 순서가 명확한 클래스라 compareTo가 작성되어 있다고 말하고 싶은 것 같습니다.

ssstopeun commented 1 year ago
public final int compareTo(E o) {
        Enum<?> other = (Enum<?>)o;
        Enum<E> self = this;
        if (self.getClass() != other.getClass() && // optimization
            self.getDeclaringClass() != other.getDeclaringClass())
            throw new ClassCastException();
        return self.ordinal - other.ordinal;
    }
gmelon commented 1 year ago

Comparable.compareTo()

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.