TreeMap实作Map接口与SortedMap接口,提供相关的方法让您有序的取出对应位置的对象,像是 firstKey()、lastKey()等方法,TreeMap是J2SE中唯一实作SortedMap接口的类别,它使用红黑树结构来对加入的对象进 行排序。
看个简单的例子:
package onlyfun.caterpillar; import java.util.*; public class TreeMapDemo { public static void main(String[] args) { Map< String, String> map = new TreeMap< String, String>(); map.put("justin", "justin's message!!"); map.put("momor", "momor's message!!"); map.put("caterpillar", "caterpillar's message!!"); Collection collection = map.values(); Iterator iterator = collection.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
由于您加入的是String对象,执行结果会自动依key的字典顺序进行排序的动作:
caterpillar's message!! justin's message!! momor's message!!
依字典顺序排序String对象是TreeMap预设的,如果您对对象有自己的一套排序顺序,您要实作一个 Comparator 对象,它有两个必须实作的方法,compare()与equals(),前者必须传回整数值,如果对象顺序相同则传回0,传回正整数表示compare ()方法的第一个对象大于第二个对象,反之则传回负整数,后者则是定义两个对象是否相等。