gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:15:39 25 4
gpt4 key购买 nike

我的代码中有以下字段:

private static final int NUM_NANOSECONDS_IN_MILLISECOND = 1000000;

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

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

最佳答案

常量就是有名称的常量。枚举是具有值的文字常量。我解释一下...

考虑:

public final static int NORTH = 0;
public final static int SOUTH = 1;
public final static int EAST = 2;
public final static int WEST = 3;

public enum Direction {
NORTH, SOUTH, EAST, WEST
}

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

if(direction == NORTH)

或使用枚举:

if(direction == Direction.NORTH)

可能出错的地方是,使用最终常量,您也可以这样做

if(direction == 0)

现在,即使代码做了同样的事情,理解它也变得更加困难。对于枚举,你不能这样做,所以会出现问题。

类似地,当期望方向作为方法参数时:

最终静态:

public void myMethod(int direction)

以及枚举:

public void myMethod(Direction direction)

更清晰,出现问题的机会更少。

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

示例:

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

那么在你的代码中:

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

moveThePlayer(p, Direction.NORTH);

这对于final static来说真的很难做到。或者至少,它变得非常难以阅读。

话虽如此,根据您正在处理的特定情况,如果只有一个数字常量值,我会保留最终的静态值。如果只有一个值,则没有必要使用枚举。

关于java - 什么时候应该使用final关键字而不是枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com