Android enumeration advantages and disadvantages and alternative solutions
Enumeration should not be used on Android, which occupies memory. Replace it 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?
1 public class SexTest {2 3 public static enum Sex {4 MAN, WOMEN 5} 6 7 private Sex sex; 8 // set Sex 9 public void setSex (sex) {10 this. sex = sex; 11} 12 13 // get Gender 14 public String getSex () {15 if (Sex. MAN = sex) return "male"; 16 if (Sex. WOMEN = sex) return "female"; 17 return "unknown"; 18} 19 20 public static void main (String [] args) {21 // The input parameter here must be an enumeration constant 22 in the Sex enumeration class. // The input is definitely not allowed. The constant 23 setSex (Sex) defined in the Sex enumeration is not allowed. MAN); 24 String resultSex = getSex (); 25 System. out. println ("resultSex:" + resultSex); 26 // output: resultSex: Male 27} 28}
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; @ Overrideprotected 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 "" ;}}@ 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,@SEX
Annotations can be placed in attribute definitions, parameters, return values, and other places to restrict data types. If we assignInt
ParametersetSex()
IDE directly reports the following error: