枚举int模式

来源:互联网 发布:oracle筛选重复数据 编辑:程序博客网 时间:2024/05/17 02:54

在枚举类型(enum)还没有引入的时候,也就是在JDK1.5以前,表示枚举类型的常用模式是声明一组具名的int常量。

下面是一个具体的例子,该类表示一段文本(text),该文本具有一些样式,比如加粗,加删除线,加下划线等。

public class Text {//位域枚举常量public static final int STYLE_BOLD      = 1 << 0; // 1public static final int STYLE_ITALIC    = 1 << 1; // 2public static final int STYLE_UNDERLINE = 1 << 2; // 4public static final int STYLE_STRIKE    = 1 << 3; // 8private int styles;public void applyStyles(int styles) {this.styles |= styles;}@Overridepublic String toString() {StringBuilder sb = new StringBuilder();sb.append("Text Style:");if((styles & STYLE_BOLD) != 0) {sb.append("-bold");}if((styles & STYLE_ITALIC) != 0) {sb.append("-italic");}if((styles & STYLE_UNDERLINE) != 0) {sb.append("-underscore");}if((styles & STYLE_STRIKE) != 0) {sb.append("-strike");}return sb.toString();}public static void main(String[] args) {Text text = new Text();text.applyStyles(Text.STYLE_BOLD | Text.STYLE_UNDERLINE);System.out.println(text);}}
输出:Text Style:-bold-underscore


如果想应用多于1个的样式,可以用|操作符进行连接。如果想知道该文本是否应用了某个样式,可以用&操作符来验证。

注意到每个常量值是2的倍数,并且该类型为int,一共有32位。那么以上样式用二进制表示如下:

STYLE_BOLD:

0000 0000 0000 0000 0000 0000 0000 0001

STYLE_ITALIC:

0000 0000 0000 0000 0000 0000 0000 0010

STYLE_UNDERLINE:

0000 0000 0000 0000 0000 0000 0000 0100

STYLE_STRIKE:

0000 0000 0000 0000 0000 0000 0000 1000


假如应用加粗,斜体和下划线样式:

int styles = STYLE_BOLD | STYLE_ITALIC | STYLE_STRIKE

因为 1 | 0 = 1 , 1 | 1 = 1 , 0 | 0 = 0

所以 styles = 0000 0000 0000 0000 0000 0000 0000 1011  // 11

如果想判断该样式是否包含某种样式,则将该样式与具体样式进行&运算。

比如判断是否应用了加粗样式:

0000 0000 0000 0000 0000 0000 0000 1011 & 0000 0000 0000 0000 0000 0000 0000 0001 = 0000 0000 0000 0000 0000 0000 0000 0001

即 styles & STYLE_BOLD != 1 or styles & STYLE_BOLD == STYLE_BOLD

目前应用了枚举int模式的有java.nio.channels.SelectionKey,它的枚举int常量包括(OP_READ,OP_WRITE,OP_ACCEPT,OP_CONNECT),还有android.app.Notification,它的枚举int常量包括(DEFAULT_SOUND,DEFAULT_LIGHTS,DEFAULT_VIBRATE,DEFAULT_ALL)


因为枚举int模式在类型安全性和使用方便性方面没有任何帮助,所以推荐使用枚举类型来代替。