今天给大家介绍一个JDK1.5的新特性:枚举类
先来看看以下的例子:
package enumdemo;
public enum Weekdays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
上面我们就定义了一个枚举类。枚举类里面只会定义一系列的关键字,它的用法如下:
package enudemo;
public class WeekdaysDemo {
public static void main(String[] args) {
System.out.println(Weekdays.Monday);
System.out.println(Weekdays.Monday.getClass());
System.out.println(Weekdays.valueOf("Wednesday"));
System.out.println(Weekdays.valueOf("Outofdays"));
}
}
运行结果如下,可以用valueOf(String)的方式来查看是否有某个值,如果该值不存在会抛出一个异常(觉得不是很友好的设计。。。。)
这种类型对于保存一组常量的时候特别有效,即它很好地取代了以前的常量类。以下是没有枚举类之前的做法,这段代码等价于我们定义的枚举类:
package enudemo;
public final class WeekdayConstants {
public static final String Monday = "Monday";
public static final String Tuesday = "Tuesday";
public static final String Wednesday = "Wednesday";
public static final String Thursday = "Thursday";
public static final String Friday = "Friday";
public static final String Saturday = "Saturday";
public static final String Sunday = "Sunday";
public String valueOf(String str) throws IllegalArgumentException
{
if(!(WeekdayConstants.Monday.equals(str)||
WeekdayConstants.Tuesday.equals(str)||
WeekdayConstants.Wednesday.equals(str)||
WeekdayConstants.Thursday.equals(str)||
WeekdayConstants.Friday.equals(str)||
WeekdayConstants.Saturday.equals(str)||
WeekdayConstants.Sunday.equals(str)))
throw new IllegalArgumentException("Exception throws!");
return str;
}
}
大家可能会抱怨,这种枚举类不能存储多个值,即我们可能想要做到一个枚举常量,可以包含多个对应的值来里面,就比如上例,我们对外的变量可能是Monday,Tuesday之类的,实际保存的值可能是1,2,3。。。
其实还是能做到的:
package enudemo;
public enum Weekdays {
Monday(1,"Monday","Mon."),
Tuesday(2,"Tuesday","Tue."),
Wednesday(3,"Wednesday","Wed."),
Thursday(4,"Thursday","Thur."),
Friday(5,"Friday","Fri."),
Saturday(6,"Saturday","Sat."),
Sunday(0,"Sunday","Sun.");
//存放星期全称的变量
private String fullname;
//存放星期简称的变量
private String shortname;
//存放星期索引的变量
private int idx;
//Weekdays的构造函数,注意它的访问控制符必须为private
private Weekdays(int idx,String fullname,String shortname){
this.idx = idx;
this.fullname = fullname;
this.shortname = shortname;
}
/**
* 获取星期在一周中的索引值
* @return 星期的索引值, 0 - Sunday, 1 - Monday, .... 6 - Saturday
*/
public int getIndex(){
return idx;
}
/**
* 获取星期的全称
* @return 星期的全称,如 Sunday, Monday...
*/
public String getFullName()
{
return fullname;
}
/**
* 获取星期的简称
* @return 星期的简称,如 Sun., Mon. ...
*/
public String getShortName()
{
return shortname;
}
/**
* 当我们打印这种实例时会显示它的全名
*/
public String toString()
{
return fullname;
}
}
这样,我们的枚举类就比较完整。
不过仍然有美中不足的地方,比如我们不能重写默认的equals方法。所有枚举类的equals方法都是写死的,如果我们想要自定义对比的方法,只能够写一个类似的公有方法。
而且枚举类也不可以继承或者实现接口,所以对于重用方面效果较差。
不过对于保存静态值来说,它还是很好用的,推荐大家尝试一下今后用它来保存常量。