Java:Enum vs. Int [英] Java: Enum vs. Int

查看:140
本文介绍了Java:Enum vs. Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中使用标志时,我已经看到两种主要方法。一个使用int值和一行if-else语句。另一个是使用枚举和case-switch语句。

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.

我想知道在使用枚举与int之间的内存使用率和速度方面是否有差异?

I was wondering if there was a difference in terms of memory usage and speed between using enums vs ints for flags?

推荐答案

ints code>可以同时使用switch或if-then-else,内存使用量对于两者来说也是最小的,速度是相似的 - 它们之间没有显着差异。

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.

但是,最重要的区别是类型检查。 枚举被检查, ints 不是。

However, the most important difference is the type checking. Enums are checked, ints are not.

这个代码:

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);

使用 public static final pattern:

There are three main problems with using the public static final pattern:


  • 问题发生在运行时,而不是编译 ,所以修复更昂贵,更难找到原因

  • 你必须编写代码来处理不好的输入 - 通常是一个 if-then-否则与最终 else throw new IllegalArgumentException(未知颜色+颜色); - 再次昂贵

  • 没有什么可以防止常量的冲突 - 即使 YELLOW GREEN 都可以编译上述类代码,相同的值 3

  • 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:


  • 您的代码将无法编译,除非您在

  • 不需要任何特殊的错误输入代码 - 编译器为您处理

  • 枚举值为un ique

这篇关于Java:Enum vs. Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆