Enum equals() and ==

This question already has an answer here:

  • Comparing Java enum members: == or equals()? 15 answers

  • == should work fine with enums because there aren't multiple references of a given enum item; there's just one. The Java Language Specification section on enum types, 8.9 states that they are implicitly static and final and so can only be created once.


    You are comparing enum constants . This means that for each enum constant, there is a single instance created.

    This

    enum Drill{
        ATTENTION("Attention!"), AT_EASE("At Ease"); 
        ...
    }
    

    is more or less equivalent to

    final class Drill {
        public static final Drill ATTENTION = new Drill("Attention!") {};
        public static final Drill AT_EASE = new Drill("At Ease") {};
        ...
    }
    

    The valueOf method

    /**
    * Returns the enum constant of this type with the specified
    * name.
    * The string must match exactly an identifier used to declare
    * an enum constant in this type.  (Extraneous whitespace 
    * characters are not permitted.)
    * 
    * @return the enum constant with the specified name
    * @throws IllegalArgumentException if this enum type has no
    * constant with the specified name
    */
    public static E valueOf(String name);
    

    returns the value of instance referred to by the variable whose name equals the specified String value.

    So

    Drill.valueOf("ATTENTION") == Drill.ATTENTION
    

    for every invocation of valueOf with that String value.


    Enum Types from the documentation,

    An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

    Because they are constants, the names of an enum type's fields are in uppercase letters.

    Drill d1= Drill.valueOf("ATTENTION"); // ATTENTION
    Drill d2= Drill.valueOf("ATTENTION"); // ATTENTION
    

    So d1 == d2 and d1.equals(d2) because they refer to the same constant value and that is Drill.ATTENTION .

    链接地址: http://www.djcxy.com/p/91828.html

    上一篇: java枚举是单身?

    下一篇: 枚举equals()和==