import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {
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));
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;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
lisi02....compareTo....lisi02
lisi007....compareTo....lisi02
lisi09....compareTo....lisi02
lisi09....compareTo....lisi007
lisi08....compareTo....lisi007
lisi08....compareTo....lisi09
lisi08....19
lisi09....19
lisi007....20
lisi02....22
为什么会出现lisi02....compareTo....lisi02 ?
黑马程序员_毕向东_Java基础视频教程第15天-02-集合框架(TreeSet存储自定义对象) |