TreeMap的使用
package frank; import java.lang.*; import java.util.TreeMap; /** * TreeMap的使用,跟TreeSet类似,会根据Key自动的排序,默认自然排序法。 * 判断标准根据compareTo方法,如果是自定义类作为key,那么就必须重写equals方法和compareTo方法 * Set和Map关系十分密切,Java首先实现了HashMap等集合,然后包装一个所有value为null的Map集合实现了Set集合类 * */ public class App { public static void main(String[] args)throws Exception { TreeMap tm = new TreeMap(); tm.put(2,"a"); tm.put(1,"b"); tm.put(5,"c"); System.out.println(tm); System.out.println(tm.firstEntry());//返回第一个Map.Entry System.out.println(tm.lastKey());//获得最后一个key的value System.out.println(tm.higherKey(1));//返回1前面的一个对的value "2" System.out.println(tm.lowerEntry(5));//返回5后面的一个Map.Entry System.out.println(tm.subMap(1,5));//返回1~5之间的Map.Entry(包括1) /** * 结果:{1=b, 2=a, 5=c} 1=b 5 2 2=a {1=b, 2=a} * */ } }