preface
See the current project used quite many enumerations, just have this small article to share
Why use Enum
An Enum in Java is a data type that contains a fixed set of constants. Enumerations are commonly used when we need to pre-define a set of values that represent certain data, and Enum is often used when we want to be type safe.
For example, when we want to keep constants in good use, we often use enums to verify type safety at compile time
Disadvantages of using Enum
On the Android developer website, there’s a quote
enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.
Each value in Enum is an object, and each declaration uses some runtime memory to simply refer to that object, so Enum takes up more memory than static int.
Adding a single Enum increases the size of the final DEX file (13 times that of static int).
The solution
Google provides a library of annotations to help us solve the Enum problem with Typedef, which ensures that a particular parameter, return value or field references a particular set of constants, and also completes the code to automatically provide allowed constants.
We can use @intdef and @stringdef to help us check variable assignments like Enum at compile time.
Use the pose
- First we need to rely on the annotation library
Dependencies {the compile ‘com. Android. Support: support – annotations: 24.2.0’}
- I’ll just go to the code, because it’s pretty simple
public class Person { public static final int MALE = 0; public static final int FEMALE = 1; private int sex; Public String getSexValue(){if(MALE == sex){return "MALE "; Else if(FEMALE == sex){return "FEMALE "; } return ""; } public void setSex(@sexDef int sex) { this.sex = sex; // RetentionPolicy.CLASS annotations are reserved to the CLASS file, but are discarded when the JVM loads the CLASS file, which is the default life cycle; RUNTIME annotations are not only saved to the class file, but still exist after the JVM loads the class file. // RetentionPolicy.SOURCE annotations are only kept in the SOURCE file. When Java files are compiled into class files, annotations are discarded. @retention (retentionPolicy.source) // Use @intdef definition to declare constants as enumerations @intdef ({MALE, FEMALE}) public @interface sexDef{}}Copy the code
- When we call setSex to set gender, if the input is not the specified type, the compilation will not pass
conclusion
The use of enums adds at least twice as many bytes to the entire APK and uses 5 to 10 times as much RAM memory as normal static constants. Therefore, you are advised to avoid using Enum. If you need to use the preceding feature, use @intdef or @stringdef instead.
For more, see The Price of ENUMs