枚举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
注意到每个常量值是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模式在类型安全性和使用方便性方面没有任何帮助,所以推荐使用枚举类型来代替。
- 枚举int模式
- JAVA 枚举 String-int
- 枚举,int ... X,ScheduledExecutorService
- 枚举继承自int
- 枚举enum 赋值 int
- 枚举与int的互换
- c++ int转换为枚举类型
- java 枚举类型与int转换
- 策略枚举模式
- 枚举单例模式
- 枚举单例模式
- 枚举取值(根据枚举的int值取出string值|根据枚举的string值取出int值)
- 享元模式和枚举
- JAVA枚举单例模式
- 单例模式---枚举式
- 单例模式枚举写法
- BlendMode颜色混合模式枚举值
- c#中枚举和int之间的相互转换
- 死锁的防止方法
- PHP JSON格式数据交互实例详解
- Linux下配置安装NFS
- NET面向对象基础托管和数据类型
- umount 时出现"Device is busy"的解法 [转]
- 枚举int模式
- POJ 2886 Who Gets the Most Candies?
- Oracle sys和system用户、sysdba 和sysoper系统权限、sysdba和dba角色的区别 .
- 使用 Python 实现多进程
- SolrCloud你值得拥有,性能表现良好
- ORA-12514 TNS 监听程序当前无法识别连接描述符中请求的服务
- ssh-极度优化iOS设备的内存(支持全系列iOS产品和固件)更新iOS5.0.1全自动优化
- ViewPager禁止手势滑动、解决和子View的滑动冲突
- [js]encodeURIComponent()的使用