Posts

Showing posts with the label enum

Using EnumSet by Example

In previous example I have explained using enum using color constants. Java util collection has provides EnumSet , it is a specialized Set implementation for use with enum types. In this post I have explained usage of EnumSet using an example. A text can have multiple attributes like bold, italic, underlined etc. Given a text can have these properties, defined a sample Text class with bit fields as text properties public class Text { //defining Text properties using int public static final int BOLD = 1<<0; public static final int ITALIC = 1<<1; public static final int UNDERLINED = 1<<2; private int style; public Text( int style){ this .style = style; } public boolean isBold(){ return (BOLD&style)==BOLD; } public boolean isItalic(){ return (ITALIC&style)==ITALIC; } public boolean isUnderlined(){ return (UNDE...

Java Enum in details

Java 5 has brought linguistic support for enumerated types. An enum type is a type whose fields consist of a fixed set of constants. The enum provides following features Typesafe Namespace Printable constants values Typical and often enum is being used to replace int constants. For example constants for color codes public static final int RED = 0; public static final int GREEN = 1; public static final int BLUE = 3; public static final int WHITE =4; public static final int BLACK = 6;   This code can be replaced by following enum public enum StandardColor { RED,GREEN,BLUE,WHITE,BLACK } Given the above enum declared, we can use the same to communicate the color preferences. For example we have Window class and it supports setting background color using setBackgroundColor(StandardColor color) . One can call setBackgroundColor method on Window's instance to set background color, as shown in code below public class Wind...