我想要做的是能够调整 TreeMap 中项目的键顺序,所以
- 我也许可以通过一些“静态”数据找到一个对象,这些数据不会改变
- 对象的位置(如果地图是扁平的)应该尊重它的“优先级”
以下测试用例适用于numEntries=6,但不适用于大于 7 的值。我真的不明白那里出了什么问题,但我怀疑树在一些更新/复制后会失衡。所以有人可以请教 - 是我的错还是 Scala 2.9 中的 TreeMap 有某种错误?
如果循环更新
for (i <- 1 to (numEntries - 1)) {
替换为
for (i <- (numEntries - 1) to 1 by -1) {
一切正常。所以看起来这是 TreeMap 中的错误?
import org.scalatest.FlatSpec
import collection.immutable.TreeMap
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class TreeMapTest extends FlatSpec {
//val numEntries = 6;
val numEntries = 10;
sealed case class Entry(first: Option[Int], last: Int) extends Ordered[Entry] {
def compare(that: TreeMapTest.this.type#Entry) = {
if (first.isEmpty || that.first.isEmpty) {
last compare that.last
} else {
(first.get compare that.first.get) match {
case 0 => last compare that.last
case x => x
}
}
}
def increase() = copy(first = Some(this.first.getOrElse(0) + 1))
}
type Container = TreeMap[Entry, Entry]
"TreeMap" should "allow updates" in {
var dataMap: Container = new Container() ++ (for (i <- 1 to numEntries) yield Entry(Some(0), i) -> Entry(Some(0), i))
for (i <- 1 to (numEntries - 1)) {
val key = new Entry(None, i)
dataMap.get(new Entry(None, i)) match {
case Some(e) =>
val newEntry = e.increase()
dataMap = (dataMap - key) + (newEntry -> newEntry)
case None => fail("Can not find entry " + key)
}
}
}
}