黑马程序员技术交流社区

标题: TreeSet存储自定义对象(求改正) [打印本页]

作者: 911288373    时间: 2012-12-20 20:53
标题: TreeSet存储自定义对象(求改正)
class TreeSetDemo1
{
        public static void main(String[] args)
        {
                TreeSet ts = new TreeSet();

                ts.add(new Student("lisi07",22));
                ts.add(new Student("lisi05",18));
                ts.add(new Student("lisi02",20));
                ts.add(new Student("lisi04",2));
                ts.add(new Student("lisi03",29));
                ts.add(new Student("lisi09",52));

                Iterator it = ts.iterator();
                while(it.hasNext())
                {
                        Student stu = (Student)it.next();
                        System.out.println(stu.getName()+"..."+stu.getAge());
                }
        }
}

class Student implements Comparable
{
        private String name;
        private int age;

        Student(String name,int age)
        {
                this.name = name;
                this.age = age;
        }
        public int compareTo(object obj)
        {
                if(!(obj instanceof Student))
                        throw new RuntimeException
                        Student s = (Student)obj;
                System.out.println(this.name+"...compareto..."+s.name);
                if(this.age>s.age)
                        return 1;
                if(this.age==s.age)
                {
                        return this.name.compareTo(s.name);
                }
                return -1;
        }
}


//错误是在37行。 请帮忙改正 多谢。
作者: 王小聪    时间: 2012-12-20 21:12
本帖最后由 王小聪 于 2012-12-20 21:20 编辑

throw new RuntimeException;
//加个分号可以吗

作者: 王小聪    时间: 2012-12-20 21:12
你的get(),set()方法在哪儿啊?
作者: 高境    时间: 2012-12-20 21:15
少了两个方法
public String getName()
{
    return name;

}
public int getAge()
{
    return age;
}
       
作者: 911288373    时间: 2012-12-20 22:46
高境 发表于 2012-12-20 21:15
少了两个方法
public String getName()
{

嗯。  对劲!
   马虎了

  谢谢大哥
作者: 911288373    时间: 2012-12-20 22:47
王小聪 发表于 2012-12-20 21:12
throw new RuntimeException;
//加个分号可以吗

多谢兄弟




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2