2015-06-20 76 views
1

我有一个坐标系,如这样的:如何结合并返回枚举值

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

但我觉得李这是解决这个问题的一种低效率的方式。有没有另外一种方法来结合这些不涉及循环所有枚举的方向?

我也想创建一个uncombine函数,它将反转组合。

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

所以是没有办法,我可以尝试更有效的方法?

+1

你能告诉你会有什么样的结果像Direction.NE.combine(Direction.W)Direction.N.combine(Direction.S)吗? – ppawel

+1

请注意,您的技术是不正确的:将N与SE组合使用E. –

+0

如果尝试将N与S组合,您希望返回值为多少? – bhspencer

回答

2

我认为为每个枚举值创建一个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; 
    } 
+0

我最终使用散列映射来正确映射所有坐标之间的关系。 –

0

你可以保持Map<Byte, Map<Byte, Direction>>其中xy将指标。一旦计算新的xy,获得Direction将如matrix.get(x).get(y)一样简单。

1

如果您的真实类与问题中的类一样简单,我认为最有效的方法是手动“硬编码”或预先计算(例如,在静态init块中)参数和结果之间的关系以及将其保存在地图中,然后仅引用已有的结果。