import java.util.EnumSet; // jamesprogram.java class jamesprogram { public static void main (String[] args){ // enhanced for loop // this loops through the enumeration // contants in the array cat.values() and // assign them to people for (cat people: cat.values()){ System.out.printf("%s\t%s\t%s\n", people, people.getDesc(), people.getYear()); } System.out.println("\n.. and now to a range of constants\n"); // loops through a new array created by the range method of the EnumSet class for (cat people: EnumSet.range(cat.emma, cat.bernard)){ System.out.printf("%s\t%s\t%s\n", people, people.getDesc(), people.getYear()); } } }
//cat.java // the enum allows us to use the class in // a specific way public enum cat { // declare constants of the enum type // i.e. variables that never change james("java","37"), emma("xml","40"), george("php","100"), bernard("excel","76"), matthew("perl","19"); // final, we don't want this changed // these two declared variables represent // the two arguments above private final String desc; private final String year; //now have a enumeration constructor cat(String description, String theirYear){ desc = description; year = theirYear; } public String getDesc(){ return desc; } public String getYear(){ return year; } }
Outputs:
emma xml 40
george php 100
bernard excel 76
matthew perl 19
.. and now to a range of constants
emma xml 40
george php 100
bernard excel 76
As we can see
EnumSet.range(cat.emma, cat.bernard)
creates a new array and is the range of values (inclusive) between emma and bernard.