스터디/이펙티브 자바

[Effective Java] Item35. ordinal 대신 인스턴스 필드

📝 작성 : 2022.06.26  ⏱ 수정 : 
728x90
public enum Role {
    CUSTOMER, SHOP_MANAGER;

    public int getAuth() { return ordinal(); }
}

알바(PART_TIMER)를 추가

public enum Role {
    CUSTOMER, PART_TIMER, SHOP_MANAGER;

    public int getAuth() { return ordinal(); }
}

문맥상 손님과 가게 사장 중간에 와야하므로 중간에 알바를 추가하면 순서가 달라지기 때문에 ordinal()메서드의 값이 달라짐

이 경우 ordinal()대신 인스턴스 필드에 값을 저장

public enum Role {
    CUSTOMER(0), SHOP_MANAGER(1);

    private final int auth;
    Role(int auth) { this.auth = auth; }

    public int getAuth() { return ordinal(); }
}

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.

반응형