Java Map的常用Map实现类之:TreeMap
1.TreeMap的特点
TreeMap存储 Key-Value 对时,需要根据 key-value 对进行排序。 TreeMap 可以保证所有的 Key-Value 对处于有序状态。 TreeMap 的 Key 的排序: ①自然排序 :TreeMap 的所有的 Key 必须实现 Comparable 接口,而且所有的 Key 应该是同一个类的对象,否则将会抛出 ClasssCastException ②定制排序 :创建 TreeMap 时,传入一个 Comparator 对象,该对象负责对 TreeMap 中的所有 key 进行排序。此时不需要 Map 的 Key 实现 Comparable 接口 TreeMap判断两个key相等的标准 :两个key通过compareTo()方法或者compare()方法返回0。 若使用自定义类作为TreeMap的key,所属类需要重写equals()和hashCode()方法,且equals()方法返回true时,compareTo()方法应返回0。
2.自然排序
实现接口的Person类,需重写hashcode()方法和equals()方法,实现Comparable接口,并重写compareTo()方法
@Override
public int compareTo ( Object o) {
if ( o instanceof Person ) {
Person p = ( Person) o;
int i = this . name. compareTo ( p. name) ;
if ( i == 0 ) {
return this . age. compareTo ( p. age) ;
}
return i;
}
return 0 ;
}
遍历排序代码
@Test
public void test ( ) {
Map map = new HashMap ( ) ;
map. put ( "AA" , 212 ) ;
map. put ( "BB" , 456 ) ;
map. put ( 123 , "CC" ) ;
map. put ( null, null) ;
map. put ( new Person ( "DD" , 23 ) , 889 ) ;
map. put ( new Person ( "DD" , 23 ) , 87 ) ;
System. out. println ( map. size ( ) ) ;
System. out. println ( map) ;
map. remove ( "BB" ) ;
System. out. println ( map) ;
map. get ( 123 ) ;
}
3.定制排序
Person类,需重写hashcode()方法和equals()方法,然后编写Comparator对象,定制需要排序对象 Comparator对象
Comparator com = new Comparator ( ) {
@Override
public int compare ( Object o1, Object o2) {
if ( o1 instanceof Person && o2 instanceof Person ) {
Person p1 = ( Person) o1;
Person p2 = ( Person) o2;
int i = p1. getAge ( ) . compareTo ( p2. getAge ( ) ) ;
if ( i == 0 ) {
return p1. getName ( ) . compareTo ( p2. getName ( ) ) ;
}
return i;
} else return 0 ;
}
} ;
将Comparator的实例对象传入TreeMap的构造器中,并进行遍历
@Test
public void test4 ( ) {
Map map = new TreeMap ( com) ;
map. put ( new Person ( "AA" , 23 ) , 49 ) ;
map. put ( new Person ( "MM" , 23 ) , 59 ) ;
map. put ( new Person ( "GG" , 23 ) , 69 ) ;
map. put ( new Person ( "JJ" , 23 ) , 79 ) ;
map. put ( new Person ( "EE" , 23 ) , 89 ) ;
Set set1 = map. keySet ( ) ;
for ( Object obj: set1) {
System. out. println ( obj+ "---->" + map. get ( obj) ) ;
}
}