JAVA枚举类的简单使用

2018-03-01 11:11:48来源:oschina作者:刘太刚人点击

分享
枚举类简介

枚举类型是Java 5中新增特性的一部分,它是一种特殊的数据类型。之所以特殊是因为它既是一种类(class)类型却又比类类型多了些特殊的约束,但是这些约束的存在也造就了枚举类型的简洁性、安全性以及便捷性。


枚举类的简单应用
1、常量的使用
enum Day {
MON, TUE, WED,
THU, FRI, SAT, SUN
}
public class Mian01 {
public static void main(String[] args) {
// 直接引用
Day day01 = Day.MON;
Day day02 = Day.THU;
Day day03 = Day.SUN;
System.out.println("-----------------toString()-------------------");
// 1、toString
System.out.println(day01.toString());
System.out.println(day02.toString());
System.out.println(day03.toString());
System.out.println("-----------------ordinal()-------------------");
// 2、ordinal()
System.out.println(day01.ordinal());
System.out.println(day02.ordinal());
System.out.println(day03.ordinal());
System.out.println("------------------name()--------------------");
// 3、name()
System.out.println(day01.name());
System.out.println(day02.name());
System.out.println(day03.name());
System.out.println("-----------------compareTo()------------------");
// 4、compareTo()
System.out.println(day01.compareTo(day01));
System.out.println(day01.compareTo(day02));
System.out.println(day03.compareTo(day01));
}
}

打印结果:



2、自定义函数
public enum Day {
MON("星期一", 1), TUE("星期二", 2), WED("星期三", 3),
THU("星期四", 4), FRI("星期五", 5), SAT("星期六", 6), SUN("星期日", 7);

private String chineseName;
private int number;

private Day(String chineseName, int number){
this.chineseName = chineseName;
this.number = number;
}

//重写toSting()
@Override
public String toString() {
return "chineseName:"+chineseName+" & number:"+number;
}
public String getChineseName() {
return chineseName;
}
public void setChineseName(String chineseName) {
this.chineseName = chineseName;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}public class Mian01 {
public static void main(String[] args) {
// 直接引用
Day day01 = Day.MON;
Day day02 = Day.THU;
Day day03 = Day.SUN;
System.out.println("-----------------toString()-------------------");
// 1、toString
System.out.println(day01.toString());
System.out.println(day02.toString());
System.out.println(day03.toString());
System.out.println("-----------------ordinal()-------------------");
// 2、ordinal()
System.out.println(day01.ordinal());
System.out.println(day02.ordinal());
System.out.println(day03.ordinal());
System.out.println("------------------name()--------------------");
// 3、name()
System.out.println(day01.name());
System.out.println(day02.name());
System.out.println(day03.name());
System.out.println("-----------------compareTo()------------------");
// 4、compareTo()
System.out.println(day01.compareTo(day01));
System.out.println(day01.compareTo(day02));
System.out.println(day03.compareTo(day01));
}
}

打印结果:



小小的拓展

本篇blog是非常初级的,仅仅可用于枚举的了解。如果想深入的了解枚举,可参考blog:


http://blog.csdn.net/javazejian/article/details/71333103


end

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台