Advantages and disadvantages of enumeration and alternative solutions for Android
Enumeration should not be used on Android, and memory usage should be replaced with the @ XXXDef annotation.
Disadvantages of using Enum
Each enumerated value is an object, which increases the memory consumption when it is used. Therefore, enumeration consumes more memory than Integer and String.
Using Enum will increase the size of the DEX file, which will cause more overhead during running and make our applications require more space.
If your application uses a lot of Enum, it is better to use Integer or String to replace them, but this will still cause problems.
Since we have all mentioned this, what are the better solutions?
Public class SexTest {
Public static enum Sex {
MAN, WOMEN
}
Private Sex sex;
// Set gender
Public void setSex (Sex sex ){
This. sex = sex;
}
// Obtain gender
Public String getSex (){
If (Sex. MAN = sex) return "male ";
If (Sex. WOMEN = sex) return "female ";
Return "unknown ";
}
Public static void main (String [] args ){
// The input parameter must be an enumeration constant in the Sex enumeration class.
// Constants defined in the Sex enumeration are definitely not allowed to be input.
SetSex (Sex. MAN );
String resultSex = getSex ();
System. out. println ("resultSex:" + resultSex );
// Output: resultSex: Male
}
}
Solution
Since the type of the parameter is too extensive, it is not a success if I restrict the parameter to a certain type set ?!
Yes. The @ IntDef/@ StringDef + @ interface parameter must be specified.
First, add the dependency to the build. gradle file.
Dependencies {compile 'com. android. support: support-annotations: 24.2.0 '}
The Code is as follows:
Public class MainActivity extends Activity {
Public static final int MALE = 0;
Public static final int FEMALE = 1;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main_activity );
Person person = new Person ();
Person. setSex (MALE );
(Button) findViewById (R. id. test). setText (person. getSexDes ());
}
Class Person {
@ SEX
Private int sex;
Public void setSex (@ SEX int sex ){
This. sex = sex;
}
@ SEX
Public int getSex (){
Return sex;
}
Public String getSexDes (){
If (sex = MALE ){
Return "male ";
} Else {
Return "female ";
}
}
}
@ IntDef ({MALE, FEMALE })
@ Retention (RetentionPolicy. SOURCE)
Public @ interface SEX {
}
}
If we try to pass in a value that is not within the limit when calling the setSex () method, the compilation will not pass, with an error message. Similarly, we can also use @ StringDef.
Here we can see that the @ SEX annotation can be placed in the attribute definition, parameters, return values, and other places to limit the data type. If we assign an Int parameter to setSex (), the IDE will directly report an error:
Https://www.bkjia.com/topicnews.aspx? Tid = 5
This article permanently updates link: https://www.bkjia.com/Linux/2018-02/151004.htm