Java에서 Enum 방식으로 정수 값을 상수로 저장
이 질문에 이미 답변이 있습니다.
현재 다음과 같은 방식으로 정수 상수를 만들고 있습니다.
public class Constants {
public static int SIGN_CREATE=0;
public static int SIGN_CREATE=1;
public static int HOME_SCREEN=2;
public static int REGISTER_SCREEN=3;
}
열거 형 방식으로 이것을 시도 할 때
public enum PAGE{SIGN_CREATE,SIGN_CREATE,HOME_SCREEN,REGISTER_SCREEN}
그리고 내가 사용할 때 PAGE.SIGN_CREATE
1을 반환해야합니다.
글쎄, 당신은 그렇게 할 수 없습니다. PAGE.SIGN_CREATE
1을 반환하지 않습니다. 반환 PAGE.SIGN_CREATE
됩니다. 이것이 열거 형의 요점입니다.
그러나 몇 가지 키 입력을 추가하려는 경우 다음과 같이 열거 형에 필드를 추가 할 수 있습니다.
public enum PAGE{
SIGN_CREATE(0),
SIGN_CREATE_BONUS(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);
private final int value;
PAGE(final int newValue) {
value = newValue;
}
public int getValue() { return value; }
}
그리고 PAGE.SIGN_CREATE.getValue()
0을 얻기 위해 전화 합니다.
각 열거 형 값과 연관된 정수 상수를 원하는 가장 일반적인 유효한 이유는 여전히 해당 정수를 예상하는 다른 구성 요소와 상호 운용하기 때문입니다 (예 : 변경할 수없는 직렬화 프로토콜 또는 열거 형은 테이블의 열을 나타냄 등). .
거의 모든 경우에 EnumMap
대신 사용하는 것이 좋습니다 . 문제가되거나 열거 형이 열 인덱스 또는 유사한 것을 나타내는 경우 구성 요소를 더 완벽하게 분리합니다. 나중에 (또는 필요한 경우 런타임에도) 쉽게 변경할 수 있습니다.
private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
pageIndexes.put(Page.SIGN_CREATE, 1);
//etc., ...
int createIndex = pageIndexes.get(Page.SIGN_CREATE);
일반적으로 매우 효율적입니다.
이와 같은 데이터를 열거 형 인스턴스 자체에 추가하는 것은 매우 강력 할 수 있지만 남용되지 않는 경우가 많습니다.
편집 : Bloch가이 문제를 Effective Java / 2nd edition, Item 33 : Use EnumMap
instead of ordinal indexing에서 해결했습니다 .
ordinal 을 사용할 수 있습니다 . 그래서 PAGE.SIGN_CREATE.ordinal()
반환합니다 1
.
편집하다:
이 작업의 유일한 문제는 열거 형 값을 추가, 제거 또는 재정렬하면 시스템이 중단된다는 것입니다. 많은 사람들에게 이것은 열거 형을 제거하지 않고 끝에 추가 값만 추가하므로 문제가되지 않습니다. 또한 번호를 다시 매길 필요가없는 정수 상수보다 나쁘지 않습니다. 그러나 다음과 같은 시스템을 사용하는 것이 가장 좋습니다.
public enum PAGE{
SIGN_CREATE0(0), SIGN_CREATE(1) ,HOME_SCREEN(2), REGISTER_SCREEN(3)
private int id;
PAGE(int id){
this.id = id;
}
public int getID(){
return id;
}
}
그런 다음 getID
. 그래서 PAGE.SIGN_CREATE.getID()
반환합니다 1
.
그 const 값을 이렇게 열거 형에 저장할 수 있습니다. 하지만 왜 const를 사용합니까? 열거 형을 유지하고 있습니까?
public class SO3990319 {
public static enum PAGE {
SIGN_CREATE(1);
private final int constValue;
private PAGE(int constValue) {
this.constValue = constValue;
}
public int constValue() {
return constValue;
}
}
public static void main(String[] args) {
System.out.println("Name: " + PAGE.SIGN_CREATE.name());
System.out.println("Ordinal: " + PAGE.SIGN_CREATE.ordinal());
System.out.println("Const: " + PAGE.SIGN_CREATE.constValue());
System.out.println("Enum: " + PAGE.valueOf("SIGN_CREATE"));
}
}
편집하다:
It depends on what you're using the int's for whether to use EnumMap or instance field.
- Bloch on Enum instance fields (Item 31: Use instance fields instead of ordinals)
- Bloch on EnumMap (Item 33: Use EnumMap instead of ordinal indexing)
I found this to be helpful:
http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/
public enum Difficulty
{
EASY(0),
MEDIUM(1),
HARD(2);
/**
* Value for this difficulty
*/
public final int Value;
private Difficulty(int value)
{
Value = value;
}
// Mapping difficulty to difficulty id
private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
static
{
for (Difficulty difficulty : Difficulty.values())
_map.put(difficulty.Value, difficulty);
}
/**
* Get difficulty from value
* @param value Value
* @return Difficulty
*/
public static Difficulty from(int value)
{
return _map.get(value);
}
}
if you want to be able to convert integer
back to corresponding enum
with selected value see Constants.forValue(...)
in below auto generated code but if not the answer of BlairHippo is best way to do it.
public enum Constants
{
SIGN_CREATE(0),
SIGN_CREATE(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);
public static final int SIZE = java.lang.Integer.SIZE;
private int intValue;
private static java.util.HashMap<Integer, Constants> mappings;
private static java.util.HashMap<Integer, Constants> getMappings()
{
if (mappings == null)
{
synchronized (Constants.class)
{
if (mappings == null)
{
mappings = new java.util.HashMap<Integer, Constants>();
}
}
}
return mappings;
}
private Constants(int value)
{
intValue = value;
getMappings().put(value, this);
}
public int getValue()
{
return intValue;
}
public static Constants forValue(int value)
{
return getMappings().get(value);
}
}
'program tip' 카테고리의 다른 글
ASP.NET에서 HTML / 이메일 템플릿을 설정할 수 있습니까? (0) | 2020.08.28 |
---|---|
널이 아닌 종료 문자열과 함께 printf 사용 (0) | 2020.08.28 |
jQuery .each () 인덱스? (0) | 2020.08.28 |
두 요소 사이에 연결선 그리기 (0) | 2020.08.28 |
Swift의 수학 함수 (0) | 2020.08.28 |