SlideShare a Scribd company logo
1 of 9
1
CSE 331
Enumerated types (enum)
slides created by Marty Stepp
based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
http://www.cs.washington.edu/331/
2
Anti-pattern: int constants
public class Card {
public static final int CLUBS = 0;
public static final int DIAMONDS = 1;
public static final int HEARTS = 2;
public static final int SPADES = 3;
...
private int suit;
...
public void setSuit(int suit) {
this.suit = suit;
}
}
• What's wrong with using int constants to represent card suits?
 variation (also bad): using Strings for the same purpose.
3
Enumerated types
• enum: A type of objects with a fixed set of constant values.
public enum Name {
VALUE, VALUE, ..., VALUE
}
• Usually placed into its own .java file.
• C has enums that are really ints; Java's are objects.
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
• Effective Java Tip #30: Use enums instead of int constants.
"The advantages of enum types over int constants are compelling.
Enums are far more readable, safer, and more powerful."
4
What is an enum?
• The preceding enum is roughly equal to the following short class:
public final class Suit extends Enum<Suit> {
public static final Suit CLUBS = new Suit();
public static final Suit DIAMONDS = new Suit();
public static final Suit HEARTS = new Suit();
public static final Suit SPADES = new Suit();
private Suit() {} // no more can be made
}
5
What can you do with an enum?
• use it as the type of a variable, field, parameter, or return
public class Card {
private Suit suit;
...
}
• compare them with == (why don't we need to use equals?)
if (suit == Suit.CLUBS) { ...
• compare them with compareTo (by order of declaration)
public int compareTo(Card other) {
if (suit != other.suit) {
return suit.compareTo(other.suit);
} ...
}
6
The switch statement
switch (boolean test) {
case value:
code;
break;
case value:
code;
break;
...
default: // if it isn't one of the above values
code;
break;
}
• an alternative to the if/else statement
 must be used on integral types (e.g. int, char, long, enum)
 instead of a break, a case can end with a return, or if neither is
present, it will "fall through" into the code for the next case
7
Enum methods
method description
int compareTo(E) all enum types are Comparable by order of
declaration
boolean equals(o) not needed; can just use ==
String name() equivalent to toString
int ordinal() returns an enum's 0-based number by order
of declaration (first is 0, then 1, then 2, ...)
method description
static E valueOf(s) converts a string into an enum value
static E[] values() an array of all values of your enumeration
8
EnumSet
• class EnumSet from java.util represents a set of enum values
and has useful methods for manipulating enums:
Set<Coin> coins = EnumSet.range(Coin.NICKEL, Coin.QUARTER);
for (coin c : coins) {
System.out.println(c); // see also: EnumMap
}
 Effective Java Tip #32: Use EnumSet instead of bit fields.
 Effective Java Tip #33: Use EnumMap instead of ordinal indexing.
static EnumSet<E> allOf(Type) a set of all values of the type
static EnumSet<E> complementOf(set) a set of all enum values other
than the ones in the given set
static EnumSet<E> noneOf(Type) an empty set of the given type
static EnumSet<E> of(...) a set holding the given values
static EnumSet<E> range(from, to) set of all enum values declared
between from and to
9
More complex enums
• An enumerated type can have fields, methods, and constructors:
public enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
private int cents;
private Coin(int cents) {
this.cents = cents;
}
public int getCents() { return cents; }
public int perDollar() { return 100 / cents; }
public String toString() { // "NICKEL (5c)"
return super.toString() + " (" + cents + "c)";
}
}

More Related Content

Similar to 05a-enum.ppt

arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
JayanthiM19
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
donnajames55
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
worldchannel
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 

Similar to 05a-enum.ppt (20)

Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Array in C
Array in CArray in C
Array in C
 
Ch08
Ch08Ch08
Ch08
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
GenericsFinal.ppt
GenericsFinal.pptGenericsFinal.ppt
GenericsFinal.ppt
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docxCOMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
COMPLEX AND USER DEFINED TYPESPlease note that the material on t.docx
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Module7
Module7Module7
Module7
 
core java
 core java core java
core java
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
 
Intro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technologyIntro to C# - part 2.pptx emerging technology
Intro to C# - part 2.pptx emerging technology
 
L10 array
L10 arrayL10 array
L10 array
 
Comparing two string modification functions
Comparing two string modification functionsComparing two string modification functions
Comparing two string modification functions
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 

Recently uploaded

Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Marc Lester
 

Recently uploaded (20)

A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdf
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeCon
 
BusinessGPT - Security and Governance for Generative AI
BusinessGPT  - Security and Governance for Generative AIBusinessGPT  - Security and Governance for Generative AI
BusinessGPT - Security and Governance for Generative AI
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
Rapidoform for Modern Form Building and Insights
Rapidoform for Modern Form Building and InsightsRapidoform for Modern Form Building and Insights
Rapidoform for Modern Form Building and Insights
 
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
[GeeCON2024] How I learned to stop worrying and love the dark silicon apocalypse
 
From Theory to Practice: Utilizing SpiraPlan's REST API
From Theory to Practice: Utilizing SpiraPlan's REST APIFrom Theory to Practice: Utilizing SpiraPlan's REST API
From Theory to Practice: Utilizing SpiraPlan's REST API
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
Abortion Clinic In Pretoria ](+27832195400*)[ 🏥 Safe Abortion Pills in Pretor...
 
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-CloudAlluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
Alluxio Monthly Webinar | Simplify Data Access for AI in Multi-Cloud
 
GraphSummit Milan - Neo4j: The Art of the Possible with Graph
GraphSummit Milan - Neo4j: The Art of the Possible with GraphGraphSummit Milan - Neo4j: The Art of the Possible with Graph
GraphSummit Milan - Neo4j: The Art of the Possible with Graph
 
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
 
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
 
The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
GraphSummit Milan - Visione e roadmap del prodotto Neo4j
GraphSummit Milan - Visione e roadmap del prodotto Neo4jGraphSummit Milan - Visione e roadmap del prodotto Neo4j
GraphSummit Milan - Visione e roadmap del prodotto Neo4j
 
Test Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdfTest Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdf
 
The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
Wired_2.0_CREATE YOUR ULTIMATE LEARNING ENVIRONMENT_JCON_16052024
 

05a-enum.ppt

  • 1. 1 CSE 331 Enumerated types (enum) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/
  • 2. 2 Anti-pattern: int constants public class Card { public static final int CLUBS = 0; public static final int DIAMONDS = 1; public static final int HEARTS = 2; public static final int SPADES = 3; ... private int suit; ... public void setSuit(int suit) { this.suit = suit; } } • What's wrong with using int constants to represent card suits?  variation (also bad): using Strings for the same purpose.
  • 3. 3 Enumerated types • enum: A type of objects with a fixed set of constant values. public enum Name { VALUE, VALUE, ..., VALUE } • Usually placed into its own .java file. • C has enums that are really ints; Java's are objects. public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } • Effective Java Tip #30: Use enums instead of int constants. "The advantages of enum types over int constants are compelling. Enums are far more readable, safer, and more powerful."
  • 4. 4 What is an enum? • The preceding enum is roughly equal to the following short class: public final class Suit extends Enum<Suit> { public static final Suit CLUBS = new Suit(); public static final Suit DIAMONDS = new Suit(); public static final Suit HEARTS = new Suit(); public static final Suit SPADES = new Suit(); private Suit() {} // no more can be made }
  • 5. 5 What can you do with an enum? • use it as the type of a variable, field, parameter, or return public class Card { private Suit suit; ... } • compare them with == (why don't we need to use equals?) if (suit == Suit.CLUBS) { ... • compare them with compareTo (by order of declaration) public int compareTo(Card other) { if (suit != other.suit) { return suit.compareTo(other.suit); } ... }
  • 6. 6 The switch statement switch (boolean test) { case value: code; break; case value: code; break; ... default: // if it isn't one of the above values code; break; } • an alternative to the if/else statement  must be used on integral types (e.g. int, char, long, enum)  instead of a break, a case can end with a return, or if neither is present, it will "fall through" into the code for the next case
  • 7. 7 Enum methods method description int compareTo(E) all enum types are Comparable by order of declaration boolean equals(o) not needed; can just use == String name() equivalent to toString int ordinal() returns an enum's 0-based number by order of declaration (first is 0, then 1, then 2, ...) method description static E valueOf(s) converts a string into an enum value static E[] values() an array of all values of your enumeration
  • 8. 8 EnumSet • class EnumSet from java.util represents a set of enum values and has useful methods for manipulating enums: Set<Coin> coins = EnumSet.range(Coin.NICKEL, Coin.QUARTER); for (coin c : coins) { System.out.println(c); // see also: EnumMap }  Effective Java Tip #32: Use EnumSet instead of bit fields.  Effective Java Tip #33: Use EnumMap instead of ordinal indexing. static EnumSet<E> allOf(Type) a set of all values of the type static EnumSet<E> complementOf(set) a set of all enum values other than the ones in the given set static EnumSet<E> noneOf(Type) an empty set of the given type static EnumSet<E> of(...) a set holding the given values static EnumSet<E> range(from, to) set of all enum values declared between from and to
  • 9. 9 More complex enums • An enumerated type can have fields, methods, and constructors: public enum Coin { PENNY(1), NICKEL(5), DIME(10), QUARTER(25); private int cents; private Coin(int cents) { this.cents = cents; } public int getCents() { return cents; } public int perDollar() { return 100 / cents; } public String toString() { // "NICKEL (5c)" return super.toString() + " (" + cents + "c)"; } }