在TreeMap的情况下,如果将我们自己的类对象作为键传递,那么需要实现哪个接口Comparable或Comparator以及为什么?

时间:2015-08-15 12:00:51

标签: java collections treemap

如果是#34; TreeMap" ,如果将我们自己的类对象作为键传递,那么需要实现哪个接口Comparable或Comparator以及为什么?

1 个答案:

答案 0 :(得分:10)

如果构造指定比较器的df <- structure(list(id = c(1L, 1L, 2L, 2L, 3L), V1 = structure(c(1L, 2L, 1L, 3L, 1L), .Label = c("a", "b", "c"), class = "factor"), V2 = c(1L, 2L, 2L, 3L, 4L)), .Names = c("id", "V1", "V2"), class = "data.frame", row.names = c(NA, -5L)) ,那么将用于比较键。

如果构造TreeMap 而不用指定比较器,那么键必须实现TreeMap

通常情况下,如果有自然排序,密钥会实施Comparable,但您可以使用单独的类作为Comparable进行自定义排序,或者如果 对于密钥类型没有自然顺序。密钥类型实现Comparator本身是不寻常的。

相关问题