首页 > 解决方案 > 当我想插入相同的键时,如何增加 TreeMap 的键?

问题描述

我有一个 TreeMap,其中有一个 id (键)列表和更多作为值的数据。因此,当我向 TreeMap 插入键和值时,当键不在 TreeMap 中时,它会运行良好。问题是当它在那里时。我必须从新的钥匙中更新所有钥匙,所以新钥匙将在他的位置,而之前在该位置的钥匙将在下一个位置。

示例:
:1:a
:2:b
:3:c
:4:d
:5:e

插入键 3,值 f:
:1:a
:2:b
:3:f
:4:c
:5:d
:6:e

标签: javakeytreemap

解决方案


Map行为完全符合其应有的行为: a 中的每个键Map都是唯一的。意思是:没有重复的键。如果您put的条目具有已存在的键,它将覆盖旧条目。

如果您只想要一个递增的项目列表,请使用List

List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");

打印它:

for(int i=0; i<list.size(); i++) {
  System.out.println("Key: " + (i+1) + " Value: " + list.get(i));
}

当你现在想在中间插入一些东西时,只需使用addwith index:

list.add(2, "f");

打印结果:

Key: 1 Value: a
Key: 2 Value: b
Key: 3 Value: f
Key: 4 Value: c
Key: 5 Value: d
Key: 6 Value: e

推荐阅读