首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

TreeSet的施用

2012-12-24 
TreeSet的使用TreeSet是依靠TreeMap来实现的TreeSet是一个有序集合,她的元素 按照升序排列,默认是按照自然

TreeSet的使用
TreeSet是依靠TreeMap来实现的
TreeSet是一个有序集合,她的元素 按照升序排列,默认是按照自然顺序排列,也就是说TreeSet中的对象元素需要实现Comparable接口。
TreeSet类中跟HashSet类一样也没有get()方法来获取列表中的元素,所以也只能通过迭代器方法来获取。

class Student implements Comparable,Comparator{      int num;      String name;      Student(int num,String name)      {           this.num=num;           this.name=name;      }      public int compareTo(Object o)      {           Student st =(Student)o;           int result;           result= num>st.num?1:(num==st.num?0:-1);           //如果学号相等,就按姓名排列           /*if(result==0)           {                 return name.compareTo(st.name);           }*/           return result;      }      //实现Comparator接口并实现它的抽象方法      public int compare(Object o1,Object o2)      {           Student st1 =(Student)o1;           Student st2 =(Student)o2;           return st1.name.compareTo(st2.name);            }      //重写toString()方法,因为如果不重写,打印出来的是16进制代码      public String toString()      {           return "num="+num+"; name="+name;      }      public static class StudentComparator implements Comparator      {           public int compare(Object o1,Object o2)           {                 Student st1 =(Student)o1;                 Student st2 =(Student)o2;                 int result;                 result=st1.num>st2.num?1:(st1.num==st2.num?0:-1);                 if(result==0)//如果学号相等 就进行名字排序                 {                      result=st1.name.compareTo(st2.name);                 }                 return result;           }      }}


上面如果只使用学号排序,那么学号相同的就不会被打印的。

热点排行