[code=java]
package cn.itcast.utils;
import java.util.Iterator;
import java.util.TreeSet;
/*
* 按照学生的年龄进行排序,如果年龄相同则按姓名的自然顺序进行排序
*/
public class TreeSetTest {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new Student("lisi02", 22));
ts.add(new Student("lisi007", 20));
ts.add(new Student("lisi09", 19));
ts.add(new Student("lisi08", 19));
// ts.add(new Student("lisi01", 40));
for (Iterator it = ts.iterator(); it.hasNext();) {
Student s = (Student) it.next();
System.out.println(s.getName() + "::" + s.getAge());
}
}
}
//让学生实现Comparable接口,从而具备比较性
class Student implements Comparable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Object o) {
if (!(o instanceof Student)) {
throw new RuntimeException("不是学生对象");
}
Student s = (Student) o;
System.out.println(this.getName() + "...compareto..." + s.getName());
if (this.getAge() > s.getAge()) {
return 1;
}
if (this.getAge() == s.getAge()) {
return this.getName().compareTo(s.getName());
}
return -1;
}
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;
}
}
[/code]
打印结果如下:
lisi007...compareto...lisi02
lisi09...compareto...lisi02
lisi09...compareto...lisi007
lisi08...compareto...lisi007
lisi08...compareto...lisi09
lisi08::19
lisi09::19
lisi007::20
lisi02::22
疑问:lisi08为什么没有跟lisi02进行比较,而是直接和lisi007,lisi09比较 |