【发布时间】:2019-02-09 07:07:58
【问题描述】:
我正在尝试使用 TreeMap 解决编程问题,这导致我发布了这个问题。
我定义了一个以 (Int,Int) 为键,以字符串为值的 treeMap,根据元组的第一个元素定义了 treeMap 排序。 而且我插入了两个不同Key的元素,但是最终的treeMap只包含一个元素。这是treeMap的定义行为吗
Scala 代码:(版本:2.12.3)
val a = scala.collection.mutable.TreeMap[(Int, Int), String]()(Ordering.by(x => x._1))
a.put((9, 21), "value-1")
a.put((9, 10), "value-2")
println(a.size) // 1
我在 java 中尝试过相同的实现,但它报告 Map Size 为 2 这是我的java代码:
如果我遗漏了一些东西,有人可以建议
import java.util.Comparator;
import java.util.TreeMap;
public class JavaTreeMapTest {
public static void main(String[] args) {
class Tuple {
Integer a;
Integer b;
public Tuple(Integer a, Integer b) {
this.a = a;
this.b = b;
}
}
Comparator<Tuple> testComparator = new Comparator<Tuple>() {
@Override
public int compare(Tuple arg0, Tuple arg1) {
if (arg0.a > arg1.a) {
return arg0.a;
} else
return arg1.a;
}
};
TreeMap<Tuple, String> tm = new TreeMap<Tuple, String>(testComparator);
tm.put(new Tuple(100, 100), "value-1");
tm.put(new Tuple(100, 101), "value-2");
System.out.println(tm.size()); //2
}
}
【问题讨论】:
-
Ordering.by()是不需要的,因为Tuple2[Int,Int]的自然顺序已经是_1。二级订单密钥为_2。