TreeMap实现了Map接口,还实现了NavigableMap以及Abstract类。 映射是根据其键的自然顺序或通过提供初始化时间的比较器进行排序的。 就时间复杂度而言,此实现为containsKey,get,put和remove操作提供了log(n)成本。 请务必注意,TreeMap不会同步,因为如果地图被多个线程访问,并且如果至少胎面在结构上修改了地图,则必须在外部进行同步。

有关TreeMap的要点
TreeMap实现Map接口。TreeMap不允许使用空键。 而是,抛出NullPointerException。 虽然,多个空值可以与不同的键关联。TreeMap是 Java 集合框架的成员。
TreeMap的继承图

TreeMap继承图
TreeMap中的构造方法摘要
TreeMap():使用其键的自然顺序构造一个新的空树映射。TreeMap(Comparator<? super K> comparator):构造一个新的空树映射,根据给定的比较器排序。TreeMap(Map<? extends K, ?extends V> m)::构造一个新的树映射,该树映射包含与给定图相同的映射,并根据其键的自然顺序进行排序。TreeMap(SortedMap<K, ? extends V> m):构造一个新的树映射,该树映射包含与指定排序图相同的映射并使用相同的排序。
TreeMap类中的方法
void clear():删除树形图中的所有元素。Object clone():返回TreeMap实例的浅表副本。Comprator<? super K> comparator:返回用于对当前映射中的键进行排序的比较器;如果映射使用其键的自然排序,则返回null。boolean containsKey(Object key):如果当前树映射中存在指定的键,则返回true。boolean containsValue(Object value):如果当前任意一个地图键都存在指定值,则返回true。V put(K key, V value):将指定的值放入指定的键。V remove(Object key):从当前映射中删除指定的键。V replace(K key, V value):仅当当前映射到某个值时,才替换指定键的条目。int size():获取当前树形图具有的元素数。Collection<V> values():返回当前映射中包含的值的集合视图。
有关EnumSet主要方法的更多信息,请随时访问原始 Oracle 文档。
使用containsKey()和containsValue()检查当前树形图是否包含指定的键或值,并使用put()填充TreeMap
import java.util.*;public class TreeMapExample {public static void main(String[] args){TreeMap<Integer, String> treeMapExample =new TreeMap<Integer, String>();// assing values to keystreeMapExample.put(5, "java");treeMapExample.put(15, "tutorial");treeMapExample.put(20, "dot");treeMapExample.put(25, "net");System.out.println("Current stage of the treeMap: " + treeMapExample);// Checking for the key '15'System.out.println("Is key 15 present in the map: " +treeMapExample.containsKey(15);// Checking for the key '5'System.out.println("Is the key 5 present? " +treeMapExample.containsKey(5));// Checking for value "java"System.out.println("Is the value 'java' present? " +treeMapExample.containsValue("java"));// Checking for value "tutorial"System.out.println("Is the value 'tutorial' present? " +treeMapExample.containsValue("tutorial"));}}
输出:
Is the key 15 present? trueIs the key 5 present? trueIs the value 'java' present? trueIs the value 'tutorial' present? true
使用remove()从TreeMap中删除元素
import java.util.*;public class treeMapExample {public static void main(String args[]) {TreeMap<Integer,String> treeMap=new TreeMap<Integer,String>();// populating the tree map using put()map.put(5,"Joe");map.put(10,"Mike");map.put(15,"Antony");System.out.println("Before remove(): ");// looping through the tree map so we can get each elementfor(Map.Entry m:map.entrySet()){// print key and valueSystem.out.println(m.getKey()+" "+m.getValue());}map.remove(15);System.out.println("After remove(): ");for(Map.Entry m:map.entrySet()){// print key and valueSystem.out.println(m.getKey()+" "+m.getValue());}}}
输出:
Before remove:5 Joe10 Mike15 AntonyAfter Remove5 Joe10 Mike
