本帖最后由 胡卿 于 2012-6-18 14:49 编辑
- import java.util.*;
- class Student implements Comparable
- {
- private String name;
- private int age;
- private int grade;
- public int compareTo(Object obj)
- {
- Student s = (Student)obj;
- int num = new Integer(this.grade).compareTo(new Integer(s.grade));
- return num==0?new Integer(this.age).compareTo(new Integer(s.age)):num;
- }
- public Student(String name,int age,int grade)
- {
- this.name = name;
- this.age = age;
- this.grade = grade;
- }
- public String getName()
- {
- return name;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- public int getAge()
- {
- return age;
- }
- public void setAge(int age)
- {
- this.age = age;
- }
- public int getGrade()
- {
- return grade;
- }
- public void setGrade(int grade)
- {
- this.grade = grade;
- }
- }
- class MyCompare implements Comparator
- {
- public int compare(Object o1,Object o2)
- {
- Student s1=(Student)o1;
- Student s2=(Student)o2;
- int num=new Integer(s2.getGrade()).compareTo(new Integer(s1.getGrade()));
- return num==0?new Integer(s2.getAge()).compareTo(new Integer(s1.getAge())):num;
- }
- }
- class Test6
- {
- public static void main(String[] args)
- {
- TreeSet ts= new TreeSet(new MyCompare());
- ts.add(new Student("张三",20,86));
- ts.add(new Student("李四",21,86));
- ts.add(new Student("王五",19,88));
- ts.add(new Student("周六",18,87));
- ts.add(new Student("吴七",22,95));
- //System.out.println(ts)这里不是打印集合么 ,为什么出现的是哈希值
- Iterator it=ts.iterator();
- while(it.hasNext())
- {
- System.out.println("姓名"+it.next().getName()+"年龄"+it.next().getAge()+"分数"+it.next().getGrade());//这里的方法为什么不能被识别
- }
- }
- }
复制代码 |