The enumeration class you really do?

In java5 added an enum keyword is used to define enumeration class, I believe that a small partner to learn a lot of java for a long time, but for enumeration class is empty, just know that there is such a thing, grandmother hurt uncle does not love, for it is not applied before, I believe the following demo you will certainly have a great interest in the enumeration, the brothers ash can easily and often achieved!

Use the enumeration class will be used to modify the default finala, enumeration class can not be subclassed.

  • Time Code
enum SeasonEnum{
    //定义四个实例,春,夏,秋,冬
    SPRING,SUMMER,FALL,WINTER;
}

public class JudgeTest {
    public void judge(SeasonEnum s){
        //swith语句里的表达式可以为枚举值
        switch (s)
        {
            case SPRING:
                System.out.println("春天到了,又到了动物交配的季节!");
                break;
            case SUMMER:
                System.out.println("夏天,小青蛙呱呱叫");
                break;
            case FALL:
                System.out.println("秋天,是个分手的好季节");
                break;
            case WINTER:
                System.out.println("老婆孩子热炕头ing");
                break;
        }
    }
}

public class EnumTest {
    public static void main(String[] args) {

        //打印枚举类型中的所有实例
        for (SeasonEnum s : SeasonEnum.values()) {
            System.out.println(s);
        }
        System.out.println();
        //传入指定的实例,输出方法中符合条件的结果
        new JudgeTest().judge(SeasonEnum.SPRING);
    }
}
  • operation result

Here Insert Picture Description
Java between objects is used to test for equality equalse, enumeration is used in the "=="

public class EnumTest {
    public static void main(String[] args) {
    
        SeasonEnum spring = SeasonEnum.SPRING;
        if (spring == SeasonEnum.WINTER){
            System.out.println("输入的值存在");
        }else {
            System.out.println("值不存在!");
        }
    }
}

Other methods java.lang.Enum class:

(1) int compareTo (E o
): used for comparison with the specified sequence enumeration object, the same enumeration instance only be compared to enumerate instances of the same type. If, after the enumeration object at the specified enumeration object, it returns a positive integer, if the position before the specified enumeration object, a negative integer is returned, otherwise it returns zero.
(2) String name ():
Returns the name of this enumeration instance, it is one of the names of all enumeration values listed in the definition of enumeration class, but toString method used in most cases, this method returns more results friendly.
(3) int ordinal ():
returns the enumerated value index in the enumeration class (that is, the position in the enumeration value enum declaration, enumeration value 0 indexed).

Published 47 original articles · won praise 34 · views 8855

Guess you like

Origin blog.csdn.net/weixin_42893085/article/details/105415518