TreeSet特点

来源:互联网 发布:云计算三层架构 编辑:程序博客网 时间:2024/05/11 20:38
import java.util.*;


class TreeSetTest
{
     public static void main(String[] args)
     {
           TreeSet st = new TreeSet();
           st.add(new Student("张三",26));
           st.add(new Student("王五",28));
           st.add(new Student("李四",19));
           st.add(new Student("孙悟空",21));
           st.add(new Student("如来",21));
           st.add(new Student("如来",21));
       
           for(Iterator it = st.iterator();it.hasNext();)
            {
                Student stu = (Student)it.next();
                sop(stu.getName()+"....."+stu.getAge());
            }


      }
      public static void sop(Object obj)//我发现这个方法太他妈好用啦
      {
          System.out.println(obj);
      }






}
class Student implements Comparable//实现Comparable接口,该接口强制让学生具备比较性
{
    private String name;
    private int age;


   
    
     
     Student(String name,int age)
     {
          this.name = name;
          this.age = age;
     }
     public int compareTo(Object obj)
     {
         //return 1;//怎么存 怎么取


        if(!(obj instanceof Student))
                throw new RuntimeException("不具有可比性");//抛出异常
         Student stu = (Student)obj;//强转
         System.out.println(this.name+"---conpareto---"+stu.name);
         if(this.age>stu.age)
             return 1;
         if(this.age==stu.age)
              {
                 return this.name.compareTo(stu.name);
              }
        return -1;
      }


     public String getName()
     {
          return name;
      }
     public int getAge()
     {
         return age;
     }
     

}





/*运行结果

张三---conpareto---张三
王五---conpareto---张三
李四---conpareto---张三
孙悟空---conpareto---张三
孙悟空---conpareto---李四
如来---conpareto---张三
如来---conpareto---李四
如来---conpareto---孙悟空
如来---conpareto---张三
如来---conpareto---如来
李四.....19
如来.....21
孙悟空.....21
张三.....26
王五.....28

*/

0 0
原创粉丝点击