假设我有一个ConcurrentSkipListMap
,我通过给它一个比较器来构造它,然后为它添加几个键值对。当我向地图添加一个键时,按照设计它会根据给定构造函数的比较器或它的自然顺序对值进行排序。但是,如果修改地图中包含的其中一个键,列表是否会重新排序?
即。
如果我有一张按名字排序的地图,并且我添加了"Alan"
和"Grace"
,那么它会是这样的:
[0] "Alan"
[1] "Grace"
如果我改变了"Alan"
- >列表看起来像"Turing"
示例A:
[0] "Turing"
[1] "Grace"
或例B:
[0] "Grace"
[1] "Turing"
这是任何其他自动排序数据结构的记录行为吗?
答案 0 :(得分:1)
似乎没有改变顺序:
public class TestMap implements Comparable<TestMap> {
private static int counter = 0;
private int count;
public TestMap() {
count = counter++;
}
@Override
public String toString() {
return count + "";
}
@Override
public int compareTo(TestMap o) {
return count - o.count;
}
public static void main(String[] args) throws Exception {
ConcurrentSkipListMap<TestMap, String> x = new ConcurrentSkipListMap<>();
TestMap a = new TestMap();
TestMap b = new TestMap();
x.put(a, "A");
x.put(b, "B");
System.out.println("Before");
for (Map.Entry<TestMap, String> entry : x.entrySet()) {
System.out.println("Key: " + entry.getKey() + " val: " + entry.getValue());
}
for (TestMap t : x.keySet()) {
if (t.count == 0) {
t.count = 5;
}
}
System.out.println("After");
for (Map.Entry<TestMap, String> entry : x.entrySet()) {
System.out.println("Key: " + entry.getKey() + " val: " + entry.getValue());
}
}
}
输出:
Before
Key: 0 val: A
Key: 1 val: B
After
Key: 5 val: A
Key: 1 val: B