我什么时候应该使用final关键字而不是枚举?

Evo*_*lor 2 java enums final

我的代码中有以下字段:

private static final int NUM_NANOSECONDS_IN_MILLISECOND = 1000000;
Run Code Online (Sandbox Code Playgroud)

有人告诉我,为了类型安全,我应该使用枚举.这不是我熟悉的.但如果是这种情况,我不知道何时在字段上使用final关键字是合适的.

我什么时候应该使用final关键字而不是枚举?

dim*_*414 6

使用枚举避免使用int,而不是final.使用专用枚举提供类型安全性,因此您可以使用更清晰的方法签名并避免错误. final用于防止一旦设置更改值,并且无论变量的类型如何,都是一种良好的做法.

在这种情况下,我不确定枚举给你的价值. NUM_NANOSECONDS_IN_MILLISECOND似乎它不应该是一个专用类型,正如@BoristheSpider建议的那样,你根本不需要这个字段.也许你的关联是使用一个枚举为单位(例如提示NANOSECOND,MILLISECOND等)而不是存储这样的比率.在这种情况下,现有的TimeUnit枚举绝对是你的朋友.


mpr*_*vat 6

常量只是具有名称的常量.枚举是具有值的文字常量.我解释...

考虑:

public final static int NORTH = 0;
public final static int SOUTH = 1;
public final static int EAST = 2;
public final static int WEST = 3;
Run Code Online (Sandbox Code Playgroud)

public enum Direction {
    NORTH, SOUTH, EAST, WEST
}
Run Code Online (Sandbox Code Playgroud)

从可读性的角度来看,它看起来有点相同:

if(direction == NORTH)
Run Code Online (Sandbox Code Playgroud)

或者使用枚举:

if(direction == Direction.NORTH)
Run Code Online (Sandbox Code Playgroud)

事情可能出错的地方是最终常数,你也可以这样做

if(direction == 0)
Run Code Online (Sandbox Code Playgroud)

现在,即使它做同样的事情,也很难理解代码.有了枚举,你就是不能这样做,所以它会让问题出现.

同样,当期望方向作为方法参数时:

最终静态:

public void myMethod(int direction)
Run Code Online (Sandbox Code Playgroud)

并使用枚举:

public void myMethod(Direction direction)
Run Code Online (Sandbox Code Playgroud)

它更清晰,问题机会也更少.

这只是一个开始.枚举实际上可以有方法帮助您更好地管理它们包含的信息.请阅读此处以获得清晰的解释.

例:

public enum Direction {
    NORTH (0, 1),
    SOUTH (0, -1),
    EAST (1, 0),
    WEST (-1, 0)

    private int xDirection, yDirection;

    Direction(int x, int y) {
        this.xDirection = x;
        this.yDirection = y;
    }

    public Vector2D getTranslation() {
        return new Vector2D(this.xDirection, this.yDirection);
    }
}
Run Code Online (Sandbox Code Playgroud)

那么在你的代码中:

public void moveThePlayer(Player p, Direction d) {
    p.translate(d.getTranslation());
}

moveThePlayer(p, Direction.NORTH);
Run Code Online (Sandbox Code Playgroud)

这真的很难做到final static.或者至少,它变得非常难以理解.

所有这一切都说,在你使用的特殊情况下,如果只有一个数值常量值,我会保持最终的静态.如果有单个值,则无需使用枚举.