如何不从TreeMap中丢失具有相同值的元素?
问题描述:
class CompoundKey implements Comparable<CompoundKey>{
String key;
Integer count;
public CompoundKey(String key, Integer count){
this.key = key;
this.count = count;
}
@Override
public int compareTo(@Nonnull CompoundKey other) {
return (other.count.compareTo(this.count));
}
}
public static void main(String[] args) {
Map<CompoundKey, Integer> map = new TreeMap<>();
map.put(new CompoundKey("a", 3), 3);
map.put(new CompoundKey("b", 1), 1);
map.put(new CompoundKey("c", 8), 8);
map.put(new CompoundKey("d", 3), 3);
map.put(new CompoundKey("e", 9), 9);
for (CompoundKey key : map.keySet()) {
System.out.println(key.key + "->" + map.get(key));
}
}
这将如下打印出:如何不从TreeMap中丢失具有相同值的元素?
e->9
c->8
a->3
b->1
在打印出的 'D-> 3' 缺失。这个实现的目的是在插入元素时创建一个按值排序的地图(我不需要在插入全部元素后对地图进行排序的实现)。
是否有我的代码的一些小的修改,不丢失具有重复值的元素?在两个重复值的情况下,排序顺序可以是随机的。
答
请确保将字符串作为您的Comparable
的一部分。例如(您确切的逻辑可能想改变):
public int compareTo(CompoundKey other) {
return other.count.compareTo(this.count) + other.key.compareTo(this.key);
}
,因为它仅在数字看起来现在,它仅会计算数字为的自然顺序。您需要包含key
作为其中的一部分。
如果整数较少,但“整数+字符串”会使比较结果翻转呢? '钥匙'的影响对我来说是不可预测的。 – user697911
再次 - 您需要调查并了解适用于您的内容,但字符串的可比较值和整数*的可比值应该是您要查找的因素。由于字符串按照字典顺序进行比较,因此可能会发生碰撞。以上述为建议,而不是权威性的,但你绝对*需要将两个值都归入你的比较。 – Makoto
是的。我有你的想法,并稍微改变了我的代码,它的工作原理。我更新了,请看看。 – user697911