java - java TreeMap什么时候进行排序?
问题描述
谁能说 TeeMap 何时进行排序 - 通过 put 方法添加条目,或者,例如,在我们迭代地图之前?我试图在 javadoc 中找到但没有运气。
解决方案
这是在更改操作期间完成的。
例如,这里是该方法的 jdk8 实现put
:
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
推荐阅读
- azure - 来自 .Net Core 的 XMLA/TMSL
- html - Bootstrap - 投资组合图像左侧,标题和描述右侧
- java - Wicket wantOnSelectionChangedNotifications 更改输入文本字段
- c# - Bearer Token Auth - 如何在控制器 ASP.NET Core 2.1 中获取登录用户值
- symfony - 树枝未定义的属性似乎不起作用
- c++ - 使用 msgpack 打包多态类结构
- c# - 如何将附件上传到服务器,Net Core+React(Redux)
- bdd - 有没有办法在一个场景中设置变量并在空手道框架的另一个场景中使用它们?
- javascript - 使用 Javascript 将 base64 图像保存到文件路径
- powershell - 在 Windows Server 2003 上使用 Where-Object 按日期过滤 Get-WmiObject