一、TreeSet的自然排序: 步骤:让元素自身具备比较性, 实现Compareable接口,覆盖其CompareTo方法
class Student implements Comparable//第一:实现Compareable接口 { private String name; private int age;
Student(String name,int age) { this.name = name; this.age = age; }
public int compareTo(Object obj) //第二:复写CompareTo方法 {
//return 0;
if(!(obj instanceof Student)) //第三:判断对象是否是特定类的一个实例 throw new RuntimeException("不是学生对象"); Student s = (Student)obj;
System.out.println(this.name+"....compareto....."+s.name); //第四:当前对象的年龄与插入对象的年龄进行比较,当前年龄大于插入对象的年龄时,返回1, 此时将插入二叉树的右边,当等于时,返回0,进行次要条件的比较,再次调用;当小于时,返回-1;
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; } }
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));
Iterator it = ts.iterator(); while(it.hasNext()) { Student stu = (Student)it.next(); System.out.println(stu.getName()+"..."+stu.getAge()); } } }
|