java - 当我想插入相同的键时,如何增加 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
解决方案
的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));
}
当你现在想在中间插入一些东西时,只需使用add
with 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