Java enum vs int

When using flags in Java, I have seen two main approaches. One uses int values and a line of if-else statements. The other is to use enums and case-switch statements. I was wondering if there was a difference in terms of memory usage and speed between using enums vs ints for flags? Both ints and enums can use both switch or if-then-else, and memory usage is also minimal for both, and speed is similar - there's no significant difference between them on the points you raised. However, the most important difference is the type checking. Enums are checked, ints are not. Consider this code:
public class SomeClass {
    public static int RED = 1;
    public static int BLUE = 2;
    public static int YELLOW = 3;
    public static int GREEN = 3; // sic

    private int color;

    public void setColor(int color) {
        this.color = color;
    }   
}
While many clients will use this properly,
new SomeClass().setColor(SomeClass.RED);
There is nothing stopping them from writing this:
new SomeClass().setColor(999);
There are three main problems with using the public static final pattern:
  • The problem occurs at runtime, not compile time, so it's going to be more expensive to fix, and harder to find the cause
  • You have to write code to handle bad input - typically a if-then-else with a final else throw new IllegalArgumentException("Unknown color " + color); - again expensive
  • There is nothing preventing a collision of constants - the above class code will compile even though YELLOW and GREEN both have the same value 3
If you use enums, you address all these problems:
  • Your code won't compile unless you pass valid values in
  • No need for any special "bad input" code - the compiler handles that for you
  • Enum values are unique
由此可见使用枚举代替int不仅可以减少代码的编写还能减少错误的产生! Found here:http://stackoverflow.com/questions/9254637/java-enum-vs-int

转载于:https://my.oschina.net/javaTechLover/blog/341617

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值