java source code Detailed enumeration Enum and Enumeration

java source code Detailed enumeration Enum and Enumeration

Class definition

public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {
}

Attribute definition

    private final String name;

    public final String name() {
        return name;
    }

    private final int ordinal;

    public final int ordinal() {
        return ordinal;
    }

    protected Enum(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
    }

    public String toString() {
        return name;
    }

    public final boolean equals(Object other) {
        return this==other;
    }
    public final int hashCode() {
        return super.hashCode();
    }

    protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    public final int compareTo(E o) {
        Enum<?> other = (Enum<?>)o;
        Enum<E> self = this;
        if (self.getClass() != other.getClass() && // optimization
            self.getDeclaringClass() != other.getDeclaringClass())
            throw new ClassCastException();
        return self.ordinal - other.ordinal;
    }

    @SuppressWarnings("unchecked")
    public final Class<E> getDeclaringClass() {
        Class<?> clazz = getClass();
        Class<?> zuper = clazz.getSuperclass();
        return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
    }

    public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                                String name) {
        T result = enumType.enumConstantDirectory().get(name);
        if (result != null)
            return result;
        if (name == null)
            throw new NullPointerException("Name is null");
        throw new IllegalArgumentException(
            "No enum constant " + enumType.getCanonicalName() + "." + name);
    }


    protected final void finalize() { }


    private void readObject(ObjectInputStream in) throws IOException,
        ClassNotFoundException {
        throw new InvalidObjectException("can't deserialize enum");
    }

    private void readObjectNoData() throws ObjectStreamException {
        throw new InvalidObjectException("can't deserialize enum");
    }
  1.  Use final modifications will no doubt have a slightly more consumed in the memory, because the constant pool after the final modification of the properties are located.

    Constant pool (constant_pool) refers be determined at compile time, and some data stored in the compiled .class files. It includes constant about classes, methods, interfaces, and the like, and also includes a symbolic reference string constants. Runtime constant pool is part of the zone method. 

    The constant pool is mainly used for storage of two categories constants: literal (Literal) and symbolic reference amount (Symbolic References), literal constant level equivalent to the concept of the Java language, such as text strings, declared as final constant value of other symbols reference compiler theory belongs to the concept of areas, including the following three types of constants: 

        1. the fully qualified name of the class and interface 

        2. Field name and descriptor 

        The method name and descriptor

Most of the eight basic types of Java wrapper class implements the constant pool technology, they are Byte, Short, Integer, Long, Character, Boolean, addition

Two kinds of floating-point types of packaging (Float, Double) is not achieved. In addition Byte, Short, Integer, Long, Character these five integers only in packaging

The corresponding values ​​in order to use the object pool 127 -128

final modification of properties: the properties of the class does not implicitly initialized (initialization class attribute must have a value) or assignment (but only one is selected) in the constructor.

     2. Compare the value of two enumeration types, you never need to call equals, direct use of "==" on it.

     3. All types are enumerated Enum subclass inherits many ways, the most useful is the toString method, which can return an enumeration constant names. As SeasonEnum.SPRING.toString return SPRING

     4. toString inverse method is a static method valueof. E.g. SeasonEnum s = Enum.valueof (SeasonEnum.class, "SPRING"), a set s SeasonEnum.SPRING

     5. ordinal method Returns enum declaration enumeration constant position, a position to start counting from 0, e.g. SeasonEnum.SUMMER.ordinal () returns 1.

     6. CompareTo type parameter used in the process, as Class class, the simplified view of the considerations, the Enum a class type parameter is omitted. In fact, enumerated types SeasonEnum should be extended to Enum <SeasonEnum>. If the enumeration constants appear before the other, it returns a negative value; if this == other, it returns 0; otherwise positive results are given in the order of enumeration constant enum declaration.

     7. Because equals, hashcode methods are final modified, it can not be enumerated rewrite (can inherit only), however, you can override the toString method.

Let's look at the basic use Java enumeration

If we set the temerity to provide a method (the outside world can change its member properties), it seems a bit contrary to the original intention of the design. So, we should abandon the set method retains the get method.

 

What enumerations are?

  Java enumeration is a kind of syntactic sugar, occurs after JDK 1.5, used to represent a fixed and finite number of objects. For example, a season like spring, summer, autumn and winter four objects; a week from Monday to Sunday seven objects. These clearly are fixed, and a finite number.

Difference enumeration class and normal class

  ①, use enum defined enumeration class inherits default java.lang.Enum categories, namely, an enumeration class is a class can not be inherited else. The general common parent class default is Object

  ②, enumeration class constructor can only use private definition, but the ordinary class can also be modified with the public

  ③, all instances of the class must show the enumeration is listed in the enumeration class (partition; end), examples of the listed systems will automatically add the default public static final modified

  ④, all provide an enumeration class values ​​() method can be used to iterate enumeration value

Use Enum class to represent the season:

public enum SeasonEnum {
	 
    //必须在第一行写出有哪些枚举值
    SPRING("春天", "春暖花开"),
    SUMMER("夏天", "炎炎盛夏"),
    FALL("秋天", "秋高气爽"),
    WINTER("冬天", "大雪纷飞");
     
    private final String name;
    private final String desc;
     
    private SeasonEnum(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }
     
    public static void main(String[] args) {
        
        System.out.println(SeasonEnum.SPRING); //SPRING
        //用 values() 来获取所有的枚举值
        for(SeasonEnum s : SeasonEnum.values()){
            System.out.println(s);
        }
    }    
}

Enum class can implement an interface:

Define an interface by returning season of the month

public interface SeasonEnumImpl {
    //用来返回季节的月份
    String getMonth();
 
}
public enum SeasonEnum implements SeasonEnumImpl{
	 
    //必须在第一行写出有哪些枚举值
    SPRING("春天", "春暖花开"){
        @Override
        public String getMonth() {
            return "12-2";
        }
    },
    SUMMER("夏天", "炎炎盛夏"){
        @Override
        public String getMonth() {
            return "3-5";
        }
    },
    FALL("秋天", "秋高气爽"){
        @Override
        public String getMonth() {
            return "6-8";
        }
    },
    WINTER("冬天", "大雪纷飞"){
        @Override
        public String getMonth() {
            return "9-11";
        }
    };
     
    private final String name;
    private final String desc;
     
    private SeasonEnum(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }
    
    public static void main(String[] args) {
        
        System.out.println(SeasonEnum.SPRING); //SPRING
         
        //用 values() 来获取所有的枚举值
        for(SeasonEnum s : SeasonEnum.values()){
            System.out.println(s.getMonth());
        }
    }
    
}

Before JDK1.6 switch statement only supports int, char, enum type, enum, make our code more readable. 

public enum Fruit {
	APPLE, BANANA, ORANGE, WATERMELON;
}
public class EnumTest {
    public static void main(String[] args)
    {
        for(Fruit fruit : Fruit.values())
        {
            test(fruit);
        }
    }
     
    public static void test(Fruit fruit)
    {
        switch (fruit)
        {
            case APPLE:
                System.out.println("This is an apple");
                break;
            case BANANA:
                System.out.println("This is a banana");
                break;
            case ORANGE:
                System.out.println("This is an orange");
                break;
            case WATERMELON:
                System.out.println("This is a watermelon");
                break;
 
            default:
                break;
        }
    }
}

 

Enumeration class source

public interface Enumeration<E> {

    boolean hasMoreElements();


    E nextElement();
}

Traversal enumeration class

Map map = request.getParameterMap();    
java.util.Enumeration  enum=this.getRequest().getParameterNames();    
       while(enum.hasMoreElements()){    
                  String  paramName=(String)enum.nextElement();                        
                  String[]  values=request.getParameterValues(paramName);    
                  for(int  i=0;i<values.length;i++){    
                  System.out.println("["+i+"]   "+paramName+"  "+values[i]);   
                  }   
       }  

   //形成键值对应的map  
  map.put(paramName, paramValue);  
  }  

​

Mybatis enumeration

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Published 370 original articles · won praise 88 · views 290 000 +

Guess you like

Origin blog.csdn.net/qq_35029061/article/details/100190890