Java教程

java枚举enum详解

本文主要是介绍java枚举enum详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package enumeratin;

public class enumeration02
{
    public static void main(String[] args)
    {
        System.out.println(Season.AUTUMN);
        System.out.println(Season.WINTER);
        //两者一样
        System.out.println(Season2.AUTUMN);
        System.out.println(Season2.SUMMER);
        Season2 spring = Season2.SPRING;
        System.out.println(spring.name());//常量名 SPRING
        System.out.println(spring.ordinal());//返回该枚举对象的次序,从0开始
        Season2[] values =Season2.values();//返回数组,含有定义的所有枚举对象
        for(Season2 season : values)//增强for循环
        {
            System.out.println(season);
        }
        Season2 winter1 = Season2.valueOf("WINTER");//返回查找到的对象,若找不到报错
        System.out.println(Season2.WINTER==winter1);//true
        //比较两个枚举常量,比较的是编号,返回编号之差
        System.out.println(Season2.WINTER.compareTo(Season2.SPRING));//3-0



    }
}

//自定义枚举实现
class Season
{
    private String name;
    private String desc;

    //定义四个对象
    public final static Season SPRING = new Season("春天","温暖");
    public final static Season SUMMER= new Season("夏天","炎热");
    public final static Season AUTUMN= new Season("秋天","凉爽");
    public final static Season WINTER = new Season("冬天","寒冷");



    //私有化,防止用户创建
    private Season(String name, String desc)
    {
        this.name = name;
        this.desc = desc;
    }

    @Override
    public String toString()
    {
        return "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}
//枚举
//enum会隐式继承 Enum类
enum Season2
{

    SPRING("春天","温暖"),
    SUMMER("夏天","炎热"),
    AUTUMN("秋天","凉爽"),
    WINTER("冬天","寒冷");
    private String name;
    private String desc;


    Season2(String name, String desc)
    {
        this.name = name;
        this.desc = desc;
    }

    @Override
    public String toString()
    {
        return "Season2{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
};
这篇关于java枚举enum详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!