Closed gmelon closed 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));
}
}
코드를 실행했을 때 아래와 같이 순서를 알 수 있게 되는데요. 순서가 명확한 값 클래스를 작성한다면 comparable인터페이스를 구현하자는 말이 핵심인 것 같아요. enum또한 순서가 명확한 클래스라 compareTo가 작성되어 있다고 말하고 싶은 것 같습니다.
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;
}
Comparable.compareTo()
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
p.87 에서
열거타입이 Comparable을 구현했다
는게 무슨 의미인지 궁금합니다. 열거타입의 필드를 자동으로 비교에 사용하는걸까요?