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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 周一川 中级黑马   /  2013-4-9 07:21  /  1441 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

在自定义的类中想要用TreeSet排序, 要提示实现ComparaTo方法 Comparable

1 个回复

倒序浏览
/*按照年龄进行排序的*/
import java.util.*;
public class TreeSetDemo
{
        public static void main(String args[]){
                TreeSet t = new TreeSet();
                t.add(new Person("zhangsan",20));
                t.add(new Person("Lisi",23));
                t.add(new Person("wangwu",45));
                t.add(new Person("haha",63));
                Iterator li = t.iterator();
                while(li.hasNext()){
                        Object obj = li.next();
                        Person pp = (Person)obj;
                        sop(pp.getName() + "...." + pp.getAge());
                }
        }
        public static void sop(Object obj){
                System.out.println(obj);
        }
}
class Person implements Comparable
{
        private String name;
        private int age;
        public Person(String name,int age){
                this.setName(name);
                this.setAge(age);
        }
        public void setAge(int age){
                this.age = age;
        }
        public int getAge(){
                return this.age;
        }
        public void setName(String name){
                this.name = name;
        }
        public String getName(){
                return this.name;
        }
        public int compareTo(Object obj){
                if(!(obj instanceof Person))
                        throw  new RuntimeException("不是Person类");
                Person p = (Person)obj;
                if(this.age>p.age){
                        return 1;
                }
                if(this.age==p.age){
                        return this.name.compareTo(p.name);
                }
                return -1;
        }
}

希望对楼主有所帮助
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马