【问题标题】:Does a ConcurrentSkipListMap sort on a key modification? (As well as other auto sorting structures)ConcurrentSkipListMap 是否对键修改进行排序? (以及其他自动排序结构)
【发布时间】:2014-11-28 21:19:15
【问题描述】:

假设我有一个ConcurrentSkipListMap,我通过给它一个比较器来构造它,然后向它添加几个键值对。当我向地图添加一个键时,根据设计,它会根据提供给构造函数的比较器或它的自然顺序对值进行排序。但是,如果我修改地图中包含的键之一,列表是否会自行重新排序?

即 如果我有一张按名字排序的地图,我添加了"Alan""Grace",它看起来像这样:

[0] "Alan"
[1] "Grace"

如果我然后更改 "Alan" -> "Turing" 列表会是什么样子

示例 A:

[0] "Turing"
[1] "Grace"

或者例子B:

[0] "Grace"
[1] "Turing"

这是记录在案的任何其他自动排序数据结构的行为吗?

【问题讨论】:

  • 如何修改密钥?去掉旧的,然后装上新的?如果是这样的话 YES。
  • 你如何定义“换钥匙”?
  • 假设您的键是对象,如果您要遍历键集,您可以修改其中一个对象中的字段。
  • 您的标题说明值修改排序。那不会发生。一切都取决于键的顺序。所以带有“Alan”的 Key[0] 仍然成为带有“Turing”的 Key[0] 的第一个条目
  • 我在标题中使用了错误的术语,我已修复它

标签: java sorting data-structures map


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多