![]() If you use enums instead of integers (or String codes), you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.īetween, overuse of enums might mean that your methods do too much (it’s often better to have several separate methods, rather than one method that takes several flags which modify what it does), but if you have to use flags or type codes, enums are the way to go. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”). What is a problem with using int constants Before. ![]() You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST), the days of the week. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. For instance, in a chess game you could represent the different types of pieces as an enum: enum ChessPiece Įnums are lists of constants. It is introduced in Java version 5 first. It is also called the Java enumeration type. An EnumMap is a compact, efficient, and fast alternative to using a HashMap with enum keys. Java enum is a special Java type that defines by a Java class. ![]() When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. The EnumMap class in Java is a specialized map implementation that is designed specifically for use with enum keys. Have you heard of Final keyword? It’s like that. Enums are lists of constants like unchangeable variables. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |