151 suggestions for improving java programs-enumeration and annotation, java151

Source: Internet
Author: User

151 suggestions for improving java programs-enumeration and annotation, java151

83. During project development, we recommend that you use enumeration to define constants instead of interface constants or class constants.

Eg: enum {Spring, Summer, Autumn, Winter ;}

Enumerated constants have the following advantages over frequently used constant classes and static constants:

1) Simpler enumeration constants: enumeration constants do not need to define enumeration values. int spring = 1; enumeration represents an enumeration item with different literal meanings. Other constants must be of the same type;

2) Enumeration constants belong to the steady state type

3) enumeration has built-in methods, such as values: obtains a set of all values, which can be used for traversal, ordinal: obtains the sorting value, compareTo comparison method, and so on;

4) enumeration can be customized: enumeration constants can not only define static methods, but also non-static methods. They can also fundamentally prevent constant classes from being instantiated.

Disadvantage: enumeration types cannot be inherited. After an enumeration constant is defined, it cannot be extended unless it is modified and reconstructed.

Enumeration traversal:

for(Season s:Season.values()){System.out.println(s);}

84. Use constructors to help describe enumeration items

Enum Season {// you can add descriptions and other definitions for enumeration items through the constructor Spring ("Spring", "Spring blossom"), Summer ("Summer", "brilliant sun shining "), autumn ("Autumn", "Autumn"), Winter ("Winter", "snow float"); private String desc; // description private String other; // others // Add the preceding description and definition. You must add the following constructor Season (String desc, String other) {this. desc = desc; this. other = other;} // obtain the description public String getDesc () {return desc;} // obtain other public String getOther () {return other ;}}

We recommend that you define a description for each enumeration item in the enumeration definition, which is more friendly and concise than adding comments to the interface constants or class constants.

85. Be careful with the null value exception caused by switch.

Public static void testSwitch (Season s) {switch (s) {case Spring: System. out. println ("Spring"); break; case Summer: System. out. println (""); break; default: throw new AssertionError ();}}

In the above Code, if testSwitch (null); is tested, a null pointer exception is thrown at switch (s, this is because the switch type that can be judged by java is short, byte, int, and char. Why can the enumeration type be compiled, this is because the compiler determines Based on the sorting values of enumeration types: Switch (s. ordinal () {case Season. spring. ordinal ()}. If it is null, there is no ordinal method, and a null pointer exception will be thrown. Therefore, the solution is to add whether it is null in this method.

86. Add the AssertionError error to the default code block of the switch.

Default:throw new AssertionError();

87. verification is required before valueOf is used.

The valueOf method is provided in the enumeration class to find enumerated items with the same string value as this parameter and return an enumerated type of data.

// Test the valueOf method. Because the Season does not exist, SpringTime will throw the // IllegalArgumentException exception information public static void testValueOf () {List <String> list = Arrays. asList ("Spring", "SpringTime"); for (String s: list) {Season season = Season. valueOf (s); if (season! = Null) {System. out. println (s);} else {System. out. println ("this enumeration type does not exist ");}}}

Solution:

1. Add the try... catch Method to the Season. valueOf Method for capture.

2. Add a method to the enumeration class to determine whether the string exists, for example, the contains method. If the string information exists, valueOf is converted to the corresponding Enumeration type. If the string information does not exist, it is not converted.

88. Simpler factory method mode with Enumeration

89. The maximum number of enumeration items is 64.

The enumeration Set provided by Java is more efficient than other Set and Map instances because the number of enumeration instances is fixed and limited:

EnumSet: the element must be an enumeration item of an enumeration.

EnumMap: the key value must be an enumerated item.

When EnumSet stores enumeration data, when the number of enumerations is less than or equal to 64, A RegularEnumSet instance object is created. If the number of enumerations is greater than 64, A JunmboEnumSet instance object is created.

Public static void testEnumSet () {EnumSet <Season> set1 = EnumSet. allOf (Season. class); EnumSet <Season> set2 = EnumSet. allOf (Season. class); // If the enumeration type Season is smaller than or equal to 64 elements, the result is: class java. util. regularEnumSetSystem. out. println (set1.getClass (); // if there are more than 64 elements in the enumeration type Season, the result is class java. util. jumboEnumSetSystem. out. println (set2.getClass ());}

Because the underlying implementation classes provided by EnumSet are basic numeric operations, their performance is certainly much better than other Set types, especially when the number is less than 64, the speed is fast.

90. Careful annotation inheritance

Meta annotation: @ Inherited, indicating whether an annotation can be automatically Inherited

91. Combination of enumeration and annotation is more powerful

// Define the role level, User, administrator, and super administrator enum RoleIdentify {User, Admin, SuperAdmin;} // define the access permission annotation class @ Retention (RetentionPolicy. RUNTIME) // Metadata Annotation, indicating the annotation retention level @ Target (ElementType. TYPE) // meta annotation, indicating where the annotation can be labeled @ Inherited // meta annotation, indicating that the annotation will be automatically Inherited @ interface Access {// defines the Access level, the default value is administrator RoleIdentify level () default RoleIdentify. admin;} // use the annotation @ Access (level = RoleIdentify. user) class TestAnnatation {} public class AnnatationTest {public static void main (String [] args) {// test TestAnnatation test = new TestAnnatation (); Access access Access = test. getClass (). getAnnotation (Access. class); System. out. println (access. level (); // print the output User }}

92. Differences between major @ Override versions

The following code:

interface MyInterface{public void doSomething();}class MyImpl implements MyInterface{@Overridepublic void doSomething() {}public void doTest(List<String> strList){}}

The above code is compiled on jdk1.6 without any problems, but The above code compilation on jdk1.5 will produce an error: The method doSomething of type MyImpl override a superclass...

The reason is that @ Override in JDK strictly complies with the overwrite definition: subclass methods and parent methods must have the same method name, input parameters, and output parameters (subclass downgrading is allowed), access permissions (allowed to expand subclass), the parent class must be a class, not an interface, otherwise it cannot be considered overwriting.

Therefore, if a project of jdk1.6 is migrated to jdk1.5, You need to delete the @ Override Annotation on the implementation interface method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.