import java.util.*;
public class TreeSetDemo15_1
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add (new Student("lisi03",39));
ts.add (new Student("lisi03",40));
ts.add (new Student("lisi007",20));
ts.add (new Student("lisi02",22));
ts.add (new Student("lisi09",19));
//ts.add (new Student("lisi08",19));
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;
}
@Override
public int compareTo(Object obj)
{
if (!(obj instanceof Student))
{
throw new RuntimeException("不是学生对象");
}
Student s=(Student)obj;
if (this.age>s.age)
return 1;
if (this.age==age) //年龄条件是主要条件
return this.name.compareTo(s.name);
你的age和name是private的 比较时应该用s.getAge()和s.getName();
帮你改了下比较方法 另外用泛型啊会舒服很多。
import java.util.*;
class TreeSetDemo15_1
{
public static void main(String[] args)
{
TreeSet<Student> ts = new TreeSet<Student>(); //泛型
ts.add (new Student("lisi03",39));
ts.add (new Student("lisi03",40));
ts.add (new Student("lisi007",20));
ts.add (new Student("lisi02",22));
ts.add (new Student("lisi09",19));
//ts.add (new Student("lisi08",19));
Iterator<Student> it = ts.iterator(); //泛型
while (it.hasNext())
{
Student stu = it.next();
System.out.println(stu.getName()+":::::"+stu.getAge());
}
}
}
class Student implements Comparable<Student> //该接口强制让学生具备比较性 //泛型
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(Student stu) //帮你改的比较方法
{
System.out.println(name+"...compareto...."+stu.getName());
int i = new Integer(age).compareTo(new Integer(stu.getAge()));
if(i == 0)
return name.compareTo(stu.getName());
return i;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
} 作者: 丁佼 时间: 2012-3-18 01:27
if (this.age==age) //年龄条件是主要条件
这句应该是this.age==s.age
import java.util.*;
class TreeSetDemo15_1
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
// ts.add("45");
// ts.add("12");
// ts.add("34");
ts.add (new Student("lisi03",39));
ts.add (new Student("lisi09",19));
ts.add (new Student("lisi03",40));
ts.add (new Student("lisi007",20));
ts.add (new Student("lisi02",22));
// ts.add (new Student("lisi08",19));
// System.out.println(ts);
Iterator it = ts.iterator();
while (it.hasNext())
{
//String name=(String)it.next();
//System.out.println(name);
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;