COP 3330 Notes 4/6
Today’s Topics Enumerations
enum webpage Since the book has nothing on enums, you can go to this page for reference instead: http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
Enumerations Sometimes we want to keep track non-standard data that can only take on a few states Examples: Seasons of the year Rock, Paper, Scissors Let's see if you can come up with an example (think assignment 3)
Enumerations One way to keep track of such data is using constants Example public static final int SPRING = 1; public static final int SUMMER = 2; public static final int FALL = 3; public static final int WINTER = 4;
Enumerations A better way can be to use an enum You can create an enumeration in much the same way as a class Example: public enum Season{ SPRING, SUMMER, FALL, WINTER }
Enumerations Problems with using int constants Not typesafe: You can store invalid values (e.g. There's no such thing as season 47) Printed values mean little (e.g. Does 2 mean Rock, Paper, or Scissors?) Adding values is error prone
Enumerations Additional benefits of enum You can use an iterator for loop over the enumerated values by using the values() method to retrieve the set of values The enumerated type can also store extra information that an int can't (constant objects could get around that, though)
Enumerations Example: Use enumerations to print out every card in a deck of cards Example: Use enumerations to print out holidays