Java 简明教程
Java TreeMap Class
Introduction
Java TreeMap 类是 Map 接口基于红黑树的实现。以下是关于 TreeMap 的重要说明 -
The Java TreeMap class is the Red-Black tree based implementation of the Map interface.Following are the important points about TreeMap −
-
The TreeMap class guarantees that the Map will be in ascending key order.
-
The Map is sorted according to the natural sort method for the key Class, or by the Comparator provided at map creation time, that will depend on which constructor used.
Class declaration
以下为 java.util.TreeMap 类的声明 -
Following is the declaration for java.util.TreeMap class −
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
Parameters
以下为 java.util.TreeMap 类的参数 -
Following is the parameter for java.util.TreeMap class −
-
K − This is the type of keys maintained by this map.
-
V − This is the type of mapped values.
Methods inherited
此类从以下类中继承方法:
This class inherits methods from the following classes −
-
java.util.AbstractMap
-
java.util.Object
-
java.util.Map
Adding and Getting a Value from a TreeMap Example
以下示例显示了 Java TreeMap get() 方法用法,用于获取映射中给定键关联的值。我们创建了一个 Integer,Integer 的 TreeMap 对象。然后添加了一些条目,然后使用 get() 为给定键打印值。
The following example shows the usage of Java TreeMap get() method to get the value associated with the given key in the map. We’ve created a TreeMap object of Integer,Integer. Then few entries are added, and using get() we’re printing a value for a given key.
package com.tutorialspoint;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
// creating tree map
TreeMap<Integer, Integer> treemap = new TreeMap<>();
// populating tree map
treemap.put(2, 2);
treemap.put(1, 1);
treemap.put(3, 3);
treemap.put(6, 6);
treemap.put(5, 5);
System.out.println("Checking value for key 3");
System.out.println("Value is: "+ treemap.get(3));
}
}
让我们编译并运行以上的程序,这会生成以下结果:
Let us compile and run the above program, this will produce the following result.
Checking value for key 3
Value is: three