TreeSet: 可以对元素排序
在对自定义对象排序时,需要实现Comparable接口,复写其compareTo方法
*intereface Comparable
* compareTo();
在compareTo()方法中定义对象间比较的依据,必要时定义主要排序和次要排序方法
在对自定义对象排序时,需要实现Comparable接口,复写其compareTo方法
*intereface Comparable
* compareTo();
在compareTo()方法中定义对象间比较的依据,必要时定义主要排序和次要排序方法
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("lisi01",40));
ts.add(new Student("lisi02",40));
for(Iterator it = ts.iterator();it.hasNext();)
{
Student stu= (Student)it.next();
System.out.println(stu.getName()+"---"+stu.getAge());
}
}
}
class Student implements Comparable
{
private String name;
private int age;
@Override
public int compareTo(Object obj) {
if(!(obj instanceof Student))
throw new RuntimeException("不是学生对象");
Student s = (Student)obj;
System.out.println(this.name+"和"+s.name+"比较");
if(this.age>s.age)
return 1;
if(this.age==s.age)
{
return this.name.compareTo(s.name);
}
return -1;
}
}