A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 王者黑桃 中级黑马   /  2014-1-14 09:52  /  614 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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)));
}
}


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马