【发布时间】:2012-09-22 14:59:06
【问题描述】:
我对十六进制网格使用整数坐标,如下所示:
object Cood
{
val up = Cood(0, 2)
val upRight = Cood(1, 1)
val downRight = Cood(1, -1)
val down = Cood(0, - 2)
val downLeft = Cood(-1, -1)
val upLeft = Cood(- 1, 1)
val dirns: List[Cood] = List[Cood](up, upRight, downRight, down, downLeft, upLeft)
}
case class Cood(x: Int, y: Int)
{
def +(operand: Cood): Cood = Cood(x + operand.x, y + operand.y)
def -(operand: Cood): Cood = Cood(x - operand.x, y - operand.y)
def *(operand: Int): Cood = Cood(x * operand, y * operand)
}
Hex 和 Sides 都有坐标值。每个 Hex 有 6 个面,但有些面将由 2 个 Hex 共享。例如 Hex(2, 2) 和它的上邻 Hex(2, 6) 共享 Side(2, 4)。所以我想应用这样的集合操作:
val hexCoods: Set[Cood] = ... some code
val sideCoods: Set[Cood] = hexCoods.flatMap(i => Cood.dirns.map(_ + i).toSet)
但如果我这样做,Cood 将被视为引用类型,并且不会删除重复的坐标。有没有办法解决这个问题?
【问题讨论】:
-
集合不包含重复项。向我们展示一些示例输入和输出以重现问题。
-
@sschaef 我看到 Set 类将 Cood 视为一种值类型。大概是因为它是一个案例类?
-
不,Cood 是一种引用类型。但是编译器会为它生成一个
equals和hashCode方法,这应该确保Set中不能有重复。
标签: scala set scala-collections