Effective Java Reading notes-enumerations and annotations

Source: Internet
Author: User

30: Use enum instead of int constant

When a fixed set of constants is required, an enum should be used instead of an int constant, except for devices with limited access to mobile phones, which should consider the performance weaknesses of the enum as appropriate.

31: Replace ordinal with instance field

You should add an int field to the enum instead of using the ordinal method to export the ordinal value associated with the enumeration. (You should hardly use the ordinal method unless you are writing an enumeration-based, generic data structure like ENUMMAP)

//wrong Public enumfruit{APPLE, PEAR, ORANGE;  Public intNumberoffruit () {returnOrdinal () + 1; }}// Right Public enumfruit{APPLE (1), PEAR (2), ORANGE (3); Private Final intNumber ; Fruit (intnum) {number =num;}  Public intNumberoffruit () {returnNumber ; }}

32: Replace bit field with Enumset

The contents of the Enumset are represented as bit vectors. If the number of enumerated types in the underlying is less than 64, the entire enumset is represented by a single long, so the performance is higher than the upper domain.

//wrong Public classtext{Private Static Final intStyle_bold = 1 << 0; Private Static Final intStyle_italic = 1 << 1; Private Static Final intStyle_underline = 1 << 2;  Public voidApplystyles (intstyles) {...}}// UseText.applystyles (Style_bold |style_italic);// Right Public classtext{ Public enumStyle{style_bold, Style_italic, style_underline} Public voidApplystyles (set<style> styles) {...}//The enumset<style> parameter is not used here because some clients might pass some other set implementations}// UseText.applystyles (Enumset.of (Style_bold, style_italic));

33: Replace ordinal index with Enummap

An ordinal index is an array index that relies on the ordinal number of an enumeration member in an enumeration, such as:

//defines the plant category, wherein the plant is divided into fruits, vegetables, trees three species Public classplant{ Public enumType {Fruit, vegetables, Tree}Private FinalString name; Private Finaltype type; Plant (String name, type type) { This. Name =name;  This. Type =type; }}set<plant>[] Plants = (set<plant>[])Newset[plant.type.valuse (). lenght];//according to the type of plant, put all the plants into three sets respectively for(inti = 0; i < plant.lenght; i++) {Plant[i]=NewHashset<plant>();} for(Plant P:garden) {//all the plants have been put in the garden .Plant[p.type.ordinal ()].add (p)//Negative:using the ordinal of the enumeration to get the desired array index, the user can not use the ordinal function in other places, and directly using the int value to access, there may be an error}    

It should be implemented using ENUMMAP, which is implemented in an array, with the rich functionality and type security of the map and the efficiency of the array:

New Enummap<plant.type, Set<plant>> (plant.type.  Class);  // constructor requires a class object of type key // according to the type of plant, put all the plants into three sets respectively  for (Plant.type type:Plant.Type.valuse ()) {   new hashset<plant>);}  for (Plant P:garden)  All Plant plant.get (p.type)are placed in the garden    . Add (p)  //  The user must use the correct key value to access, that is, type }    

When multidimensional relationships are required, enummap< can be used, ..., enummap<...>>

34: Simulating a scalable enumeration with an interface

Since enums are not extensible in Java, in some cases it may be necessary to extend the enumeration, such as the type of operation (+-*/, etc.), to consider:

    1. Define an interface, such as public interface operation{...} ;
    2. To make an enumeration inherit an interface: for example, public enum Basicoperation implements operation{...}
    3. The APIs used are written as interfaces (e.g., T extends Enum<t> & operation), not implementations (e.g. Basicoperation)
      Private Static extends void function (T-t,..); Represents T, which is a subtype of enumeration and operation

    4. When you need to extend the Basicoperation enumeration, you can write another enumeration, and the implements interface operation

35: Annotations take precedence over naming patterns

Preferential use of annotations to surface specific information for certain program elements

36: Stick with override annotations

Using the override annotation on the method you want to override, the compiler can help you find some errors. You can not write the exception of override: The abstract method of the parent class is implemented in a non-abstract class, because if there is no overwrite, the compiler will issue an error.

37: Implement type with Tag interface

Tags are divided into marker interfaces and tag annotations.

Tag interface: There is no interface that contains a method declaration, just a class that implements an interface with some kind of property. such as the Serializable interface.

The final difference between the markup interface and the markup annotation is that the markup interface can check for the appropriate type problems at compile time, while the markup annotations go to runtime.

Use: Tag annotations should be used when tags are applied to any program element, including methods, domains, and not just interfaces and classes, or in the future to add more information to annotations, or to adapt to frameworks that already use annotation types extensively, and when tags are applied only to classes and interfaces, If you define a type of markup that no new method is associated with, you should use the tag interface.

Effective Java Reading notes-enumerations and annotations

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.