Programming

안드로이드에서 열거 형 작업

procodes 2020. 7. 20. 21:24
반응형

안드로이드에서 열거 형 작업


내 앱의 안드로이드에서 작업하는 계산 활동으로 거의 끝났습니다. Gender Enum을 만들려고하는데 어떤 이유로 든 구문 오류가 발생하면 "EnumBody"를 삽입하여 EnumDeclaration을 완료하십시오.

public static enum Gender
{
    static
    {
        Female = new Gender("Female", 1);
        Gender[] arrayOfGender = new Gender[2];
        arrayOfGender[0] = Male;
        arrayOfGender[1] = Female;
        ENUM$VALUES = arrayOfGender;
    }
}

정적 {}없이 시도했지만 동일한 구문 오류가 발생합니다.


이 구문은 어디에서 찾았습니까? Java Enum은 매우 간단합니다. 값만 지정하면됩니다.

public enum Gender {
   MALE,
   FEMALE
}

더 복잡하게하려면 다음과 같이 값을 추가하면됩니다.

public enum Gender {
    MALE("Male", 0),
    FEMALE("Female", 1);

    private String stringValue;
    private int intValue;
    private Gender(String toString, int value) {
        stringValue = toString;
        intValue = value;
    }

    @Override
    public String toString() {
        return stringValue;
    }
}

그런 다음 열거 형을 사용하려면 다음과 같이하십시오.

Gender me = Gender.MALE

이 논쟁 지점에 대해 논쟁이 있었지만 가장 최근의 문서에서도 안드로이드는 안드로이드 응용 프로그램에서 열거 형을 사용하는 것이 좋지 않다고 제안합니다. 그 이유는 정적 상수 변수보다 더 많은 메모리를 사용하기 때문입니다. 다음은 2014 년 페이지의 안드로이드 응용 프로그램에서 열거 형 사용에 대해 조언하는 문서입니다. http://developer.android.com/training/articles/memory.html#Overhead

나는 인용한다 :

메모리 오버 헤드에주의

사용중인 언어 및 라이브러리의 비용과 오버 헤드에 대해 잘 알고 있으며 앱을 디자인 할 때 처음부터 끝까지이 정보를 염두에 두십시오. 종종 표면에 무해 해 보이는 것들이 실제로 많은 양의 오버 헤드를 가질 수 있습니다. 예를 들면 다음과 같습니다.

  • 열거 형은 정적 상수보다 두 배 이상의 메모리를 필요로합니다. Android에서는 열거 형을 사용하지 않아야합니다.

  • Java의 모든 클래스 (익명 내부 클래스 포함)는 약 500 바이트의 코드를 사용합니다.

  • 모든 클래스 인스턴스에는 12-16 바이트의 RAM 오버 헤드가 있습니다.

  • 단일 항목을 HashMap에 넣으려면 32 바이트를 사용하는 추가 항목 오브젝트를 할당해야합니다 (최적화 된 데이터 컨테이너에 대한 이전 섹션 참조).

여기저기서 몇 바이트가 빠르게 쌓입니다. 클래스 나 객체가 많은 앱 디자인은이 오버 헤드로 인해 어려움을 겪습니다. 그것은 힙 분석을보고 어려운 문제에 처할 수 있으며 문제를 깨닫는 것은 RAM을 사용하는 많은 작은 객체입니다.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!


As commented by Chris, enums require much more memory on Android that adds up as they keep being used everywhere. You should try IntDef or StringDef instead, which use annotations so that the compiler validates passed values.

public abstract class ActionBar {
...
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
@Retention(RetentionPolicy.SOURCE)
public @interface NavigationMode {}

public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;

@NavigationMode
public abstract int getNavigationMode();

public abstract void setNavigationMode(@NavigationMode int mode);

It can also be used as flags, allowing for binary composition (OR / AND operations).

EDIT: It seems that transforming enums into ints is one of the default optimizations in Proguard.


public enum Gender {
    MALE,
    FEMALE
}

According to this Video if you use the ProGuard you don't need even think about Enums performance issues!!

Proguard can in many situations optimize Enums to INT values on your behalf so really don't need to think about it or do any work.


Android's preferred approach is int constants enforced with @IntDef:

public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;

@Retention(RetentionPolicy.SOURCE)
@IntDef ({GENDER_MALE, GENDER_FEMALE})
public @interface Gender{}

// Example usage...
void exampleFunc(@Gender int gender) {
  switch(gender) {
  case GENDER_MALE:

     break;
  case GENDER_FEMALE:
     // TODO
     break;
  }
}

Docs: https://developer.android.com/studio/write/annotations.html#enum-annotations

참고URL : https://stackoverflow.com/questions/9246934/working-with-enums-in-android

반응형