SortedMap<K,V> subMap(K fromKey, K toKey)
描述 (Description)
subMap(K fromKey,K toKey)方法用于返回此映射部分的视图,其键的范围从fromKey(包括)到toKey(不包括)。 (如果fromKey和toKey相等,则返回的地图为空。)返回的地图由此地图支持,因此返回的地图中的更改将反映在此地图中,反之亦然。
声明 (Declaration)
以下是java.util.TreeMap.subMap()方法的声明。
public SortedMap<K,V> subMap(K fromKey,K toKey)
参数 (Parameters)
fromKey - 这是返回映射中键的低端点(包括)。
toKey - 这是返回映射中键的高端点(独占)。
返回值 (Return Value)
方法调用返回此映射部分的视图,其键的范围从fromKey(包括)到toKey(不包括)。
异常 (Exception)
ClassCastException - 如果使用此映射的比较器无法将fromKey和toKey相互比较,则抛出此异常。
NullPointerException - 如果fromKey或toKey为null并且此映射使用自然排序,或者其比较器不允许空键,则抛出此异常。
IllegalArgumentException - 如果fromKey大于toKey,则抛出此异常; 或者如果此地图本身具有受限范围,并且fromKey或toKey位于范围的边界之外。
例子 (Example)
以下示例显示了java.util.TreeMap.subMap()的用法
package com.iowiki;
import java.util.*;
public class TreeMapDemo {
public static void main(String[] args) {
// creating maps
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
SortedMap<Integer, String> treemapincl = new TreeMap<Integer, String>();
// populating tree map
treemap.put(2, "two");
treemap.put(1, "one");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(5, "five");
System.out.println("Getting a portion of the map");
treemapincl = treemap.subMap(1,5);
System.out.println("Sub map values: "+treemapincl);
}
}
让我们编译并运行上面的程序,这将产生以下结果。
Getting a portion of the map
Sub map values: {1=one, 2=two, 3=three}