java枚举enum详解
2021/9/8 20:08:18
本文主要是介绍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详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26JAVA语音识别项目资料的收集与应用
- 2024-11-26Java语音识别项目资料:入门级教程与实战指南
- 2024-11-26SpringAI:Java 开发的智能新利器
- 2024-11-26Java云原生资料:新手入门教程与实战指南
- 2024-11-26JAVA云原生资料入门教程
- 2024-11-26Mybatis官方生成器资料详解与应用教程
- 2024-11-26Mybatis一级缓存资料详解与实战教程
- 2024-11-26Mybatis一级缓存资料详解:新手快速入门
- 2024-11-26SpringBoot3+JDK17搭建后端资料详尽教程
- 2024-11-26Springboot单体架构搭建资料:新手入门教程