gpt4 book ai didi

java - 如何组合并返回枚举值

转载 作者:行者123 更新时间:2023-11-29 05:04:18 24 4
gpt4 key购买 nike

我有一个这样的坐标系:

public enum Direction {
N ( 0, 1),
NE ( 1, 1),
E ( 1, 0),
SE ( 1, -1),
S ( 0, -1),
SW (-1, -1),
W (-1, 0),
NW (-1, 1);

private int x = 0, y = 0;

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

public int getX() {
return x;
}

public int getY() {
return y;
}

public Direction combine(Direction direction) {
//unsure
}
}

我正在尝试将方向与枚举中的方法结合起来,例如:

Direction.N.combine(Direction.E) -> should become Direction.NE
Direction.N.combine(Direction.N) -> null or Direction.N again

我的想法是遍历枚举中的所有值,并找到与其 x 和 y 组合相匹配的值:

public Direction combine(Direction direction) {
Direction[] directions = Direction.values();

for (int i = 0; i < directions.length; i++)
if (x + direction.x == directions[i].x && y + direction.y == directions[i].y)
return directions[i];

return this;
}

但我觉得这是一种低效的方法。有没有另一种方法可以组合这些方向而不涉及遍历所有枚举?

我还想创建一个取消组合的函数来反转组合。

Direction.NE.uncombine() -> Direction[] {Direction.N, Direction.E}

我也可以使用相同的循环技术,例如:

public Direction[] uncombine() {
Direction[] directions = Direction.values(),
rtn = new Direction[2];

for (int i = 0; i < directions.length; i++)
if (x == directions[i].x && directions[i].y == 0)
rtn[0] = directions[i];

for (int i = 0; i < directions.length; i++)
if (y == directions[i].y && directions[i].x == 0)
rtn[1] = directions[i];

return rtn;
}

那么我可以尝试更有效的方法吗?

最佳答案

我认为创建一个 Map<Direction, Direction>对于每个枚举值,您都可以在性能和代码整洁度之间取得良好的平衡。

combine方法变为:

    public Direction combine(Direction other) {
return this.combinerMap.get(other);
}

当然,您需要在枚举类的初始化期间构建映射。

返回 null从这个方法中调用是一个坏主意,因为它将健全性检查的责任推回给调用者。所以我会这样写:

    public Direction combine(Direction other) 
throws InsaneDirectionsException{
Direction res = this.combineMap.get(other);
if (res == null) {
throw new InsaneDirectionsException(
"Can't combine directions " + this +
" and " + other);
}
return res;
}

关于java - 如何组合并返回枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30959349/

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