Java TreeMap示例
TreeMap实现了Map接口和NavigableMap以及抽象类。映射根据其键的自然顺序或者由提供初始化时间的比较器进行排序。就时间复杂性而言,此实现为containsKey、get、put和remove操作提供了log(n)成本。需要注意的是TreeMap是不同步的,因为如果映射是由多个线程访问的,并且至少有一个踏板在结构上修改了映射,那么它必须在外部同步。
树图的要点
TreeMap实现映射接口。
TreeMap不允许空键。相反,将引发NullPointerException。但是,多个空值可以与不同的键相关联。
TreeMap是Java集合框架的一个成员。
TreeMap中的构造函数摘要
TreeMap():构造一个新的空树映射,其键按自然顺序排列。
TreeMap(比较器<?super K>comparator):构造一个新的空树映射,根据给定的比较器排序。
树状图(地图<?扩展K?extends V>m):构造一个新的树映射,它包含与给定映射相同的映射,并根据其键的自然顺序排序。
树状图(SortedMap<K?extends V>m):构造一个新的树映射,它包含相同的映射,并使用与指定的排序映射相同的顺序。
TreeMap类中的方法
void clear():删除树映射中的所有元素。
Object clone():返回TreeMap实例的浅副本。
压缩机<?super K>comparator:返回用于对当前映射中的键排序的比较器,如果映射使用其键的自然顺序,则返回null。
boolean containsKey(Object key):如果当前树映射中存在指定的键,则返回true。
boolean containsValue(Object value):如果指定的值存在于当前的映射键中,则返回true。
V put(K键,V值):将指定值放入指定键。
V remove(对象键):从当前贴图中移除指定的键。
V replace(K key,V value):仅当指定键当前映射到某个值时才替换该项。
int size():获取当前树映射包含的元素数。
Collection<V>values():返回当前映射中包含的值的集合视图。
有关EnumSet的主要方法的更多信息,请访问原始的Oracle文档。
使用containsKey()和containsValue()检查当前树映射是否包含指定的键或者值,并使用put()填充树映射
import java.util.*;
public class TreeMapExample {
public static void main(String[] args)
{
TreeMap<Integer, String> treeMapExample =
new TreeMap<Integer, String>();
//assing values to keys
treeMapExample.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? true Is the key 5 present? true Is the value 'java' present? true Is 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 element
for(Map.Entry m:map.entrySet())
{
//print key and value
System.out.println(m.getKey()+" "+m.getValue());
}
map.remove(15);
System.out.println("After remove(): ");
for(Map.Entry m:map.entrySet())
{
//print key and value
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
输出
Before remove: 5 Joe 10 Mike 15 Antony After Remove 5 Joe 10 Mike

