package com.crazyfirst.jiang;
import java.util.TreeMap;
//R类重写了equals方法,如果count属性相等返回true,
//重写了compareTo(Object obj)方法,如过count属性相等返回0
class R implements Comparable{
int count;
public R(int count){
this.count=count;
}
public String toString(){
return "R(count属性:"+count+")";
}
public boolean equals(Object obj){
if(this==obj){
return true;
}
if(obj!=null&&obj.getClass()==R.class){
R r=(R)obj;
if(r.count==this.count){
return true;
}
}
return false;
}
public int compareTo(Object obj){
R r=(R)obj;
if(this.count>r.count){
return 1;
}else if(this.count==r.count){
return 0;
}else{
return -1;
}
}
}
public class TestTreeMap {
/**
* @author 王者黑桃
*/
public static void main(String[] args) {
TreeMap<R, String> tm=new TreeMap<R, String>();
tm.put(new R(3), "蒋彦涛");
tm.put(new R(-5), "任世航");
tm.put(new R(9), "黑旭鹏");
System.out.println(tm);
// 返回该TreeMap的第一个Entry对象
System.out.println(tm.firstEntry());
//返回该TreeMap的最后一个Key值
System.out.println(tm.lastKey());
//返回该TreeMap的比new R(2)大的最小Key值
System.out.println(tm.higherKey(new R(2)));
//返回该TreeMap的比new R(2)小的最大Key-value对
System.out.println(tm.lowerEntry(new R(2)));
//返回该TreeMap的子TreeMap
System.out.println(tm.subMap(new R(-1), new R(4)));
}
}
|
|