我想要一个HashMap按照我添加它们的方式订购钥匙的地方.
所以我正在使用LinkedHashMap.它具有可预测的迭代顺序.
如果使用put,插入的键将位于地图键集的末尾.
是否可以使用put,将键/对对插入特定位置?例如,我想put索引一些东西2,有效地使这对在迭代时成为第三个条目.
这是一种使用临时映射通过适当的索引处理在特定索引处插入项目的简单方法。
您也可以将其设为Generic。
public static void put(LinkedHashMap<String, String> input,
int index, String key, String value) {
if (index >= 0 && index <= input.size()) {
LinkedHashMap<String, String> output=new LinkedHashMap<String, String>();
int i = 0;
if (index == 0) {
output.put(key, value);
output.putAll(input);
} else {
for (Map.Entry<String, String> entry : input.entrySet()) {
if (i == index) {
output.put(key, value);
}
output.put(entry.getKey(), entry.getValue());
i++;
}
}
if (index == input.size()) {
output.put(key, value);
}
input.clear();
input.putAll(output);
output.clear();
output = null;
} else {
throw new IndexOutOfBoundsException("index " + index
+ " must be equal or greater than zero and less than size of the map");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8837 次 |
| 最近记录: |