package ca.map; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedList; import java.util.TreeMap; public class TreeMapDome { //1、TreeMap如不指定排序器,默认将按照key值进行升序排序,如果指定了排序器,则按照指定的排序器进行排序。 //2、具体的排序规则,开发人员可以在int compare()方法中进行指定。 public static void main(String[] args) { //不指定排序器 TreeMap<String, String> stm = new TreeMap<String, String>(); stm.put("2", "22"); stm.put("b", "BB"); stm.put("1","11"); stm.put("a", "AA"); TreeMap<String, String> stm1 = new TreeMap<String, String>(); stm1.put("2", "22"); stm1.put("b", "BB"); stm1.put("1","11"); stm1.put("a", "AA"); System.out.println(stm1.equals(stm)); System.out.println(stm==stm1); System.out.println(stm.hashCode()); System.out.println(stm1.hashCode()); System.out.println("TreeMapSortByDefault:"+stm1); System.out.println(); TreeMap<String, String> stm2 = new TreeMap<String, String>(new Comparator<String>() { /* * int compare(Object o1, Object o2) 返回一个基本类型的整型, * 返回负数表示:o1 小于o2, * 返回0 表示:o1和o2相等, * 返回正数表示:o1大于o2。 */ public int compare(String o1, String o2) { //指定排序器按照降序排列 return o2.compareTo(o1); } }); stm2.put("2", "22"); stm2.put("b", "BB"); stm2.put("1","11"); stm2.put("a", "AA"); System.out.println("TreeMapSortByDefaul2t:"+stm2); Hashtable<String,String> htb = new Hashtable<String, String>(); htb.put("1", "aa"); htb.put("2", "bb"); htb.put("3", "cc"); System.out.println("hash table:"+htb); System.out.println(); //参数initialCapacity是Hashtable的初始容量,它的值应大于0。loadFactor又称装载因子,是一个0.0到0.1之间的float型的浮点数。它是一个百分比,表明了哈希表何时需要扩充 Hashtable<String, String> hashTB = new Hashtable<String, String>(5, 0.7f); hashTB.put("1", "beijing"); hashTB.put("2", "tianjing"); hashTB.put("3", "lanzhou"); Enumeration enumer = hashTB.elements(); while(enumer.hasMoreElements()){ String s = (String) enumer.nextElement(); System.out.print(s+" "); } } }
输出为:
true
false
7398
7398
TreeMapSortByDefault:{1=11, 2=22, a=AA, b=BB}
TreeMapSortByDefaul2t:{b=BB, a=AA, 2=22, 1=11}
hash table:{3=cc, 2=bb, 1=aa}
beijing lanzhou tianjing