本帖最后由 谢文斌 于 2013-12-17 19:19 编辑
大哥,你这代码,好多单词错误,我改了半天= =占位编辑代码完毕:- package Temp;
- import java.util.Iterator;
- import java.util.Set;
- import java.util.TreeSet;
- class TreeSetDemo
- {
- public static void main(String[] args)
- {
- Student s1 = new Student("heibai", 18);
- Student s2 = new Student("小李子", 22);
- Student s3 = new Student("小太监", 20);
- Set<Student> ts = new TreeSet();
- ts.add(s1);
- ts.add(s2);
- ts.add(s3);
-
- Iterator<Student> it = ts.iterator();
- System.out.println("Name\tAge");
- while(it.hasNext())
- {
- Student s = it.next();
- System.out.println(s.getName()+"\t"+s.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 s)//当泛型 没有出现的时候,集合里可以装任意对象,所以这里要判断,出现泛型后,我们限定为Student类就可以了。
- {
- if(this.age>s.age)
- return 1;
- else if(this.age==s.age)
- return 0;
- return -1;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
复制代码 输出结果:
Name Age
heibai 18
小太监 20
小李子 22
|