复习的时候发现Java中的Enumerations这个类型以前好像没有见过,感觉有时候还是挺有用的,所以就来记录一下。
根据我的理解,Enumerations就是一个类class,但是里面可以自定义一些常用的对象。比如说我有一个课程(Course)类,然后我经常使用的对象有math,Chinese,English这三门课程,所以就可以把这三种对象定义在Enumerations里面。
public enum Course {
math("math",6,"m"),Chinese("Chinese",4,"c"),English("English",4,"e");
private final String courseName;
private final int studyHours;
private final String teacherName;
Course(String courseName,int studyHours,String teacherName) {
this.courseName=courseName;
this.studyHours=studyHours;
this.teacherName=teacherName;
}
public String getCourseName() {
return this.courseName;
}
public String getTeacherName() {
return this.teacherName;
}
public int getStudyHours() {
return this.studyHours;
}
}
像这样,我定义了一个Enumerations,里面有三个常用的对象,math,Chinese,English。如果想要调用其中一个也很容易,如下:
Course m=Course.math;
System.out.println(m.getTeacherName());
这样,m就是math这个对象了。
另外,还可以遍历这些对象,像这样:
for (Course p : Course.values()) {
System.out.println(p.getCourseName());
}
后来又发现一点,不要轻易修改里面属性的值。比如现在我把Course修改如下,让它变成一个mutable的ADT,就是把studyHours前面的final修饰符去掉,然后增加了一个修改studyHours的方法setStudyHours。
public enum Course {
math("math",6,"m"),Chinese("Chinese",4,"c"),English("English",4,"e");
private final String courseName;
private int studyHours;
private final String teacherName;
Course(String courseName,int studyHours,String teacherName) {
this.courseName=courseName;
this.studyHours=studyHours;
this.teacherName=teacherName;
}
public String getCourseName() {
return this.courseName;
}
public String getTeacherName() {
return this.teacherName;
}
public int getStudyHours() {
return this.studyHours;
}
public void setStudyHours(int hours) {
this.studyHours=hours;
}
}
然后我尝试修改属性的值:
public static void main(String[] args) {
Course m=Course.math;
m.setStudyHours(4);
System.out.println(m.getStudyHours());
System.out.println(Course.math.getStudyHours());
}
结果输出都是4。这就说明第一句的m=Course.math应该是让m指向math的空间,然后修改m的studyHours后,这个空间里的studyHours就会发生变化,所以Enumerations里面的math对象也就变化了。
因此我觉得对于Enumerations,还是使用immutable的数据类型为好。