自然排序Comparable TreeSet的排序由comparable接口的compareTo方法返回的int值确定,0表示与根节点相同,不予存储;正数表示比根节点数据大,存在右节点;负数表示比根节点数据大,存在左节点package Set925.TreeSetDemo;public class Student implements Comparable<Student>{ private String name; private int age; 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; } public Student(String name, int age) { this.name = name; this.age = age; } public Student() { } @Override public int compareTo(Student o) { int num=this.age-o.age; int num2=num==0?this.getName().compareTo(o.getName()):num; return num2; }}package Set925.TreeSetDemo;import java.util.TreeSet;public class TreeSetDemo { public static void main(String[] args) { Student s1=new Student("王昭君",18); Student s2=new Student("貂蝉",16); Student s3=new Student("西施",17); Student s4=new Student("杨玉环",20); Student s5=new Student("小乔",18); TreeSet<Student> ts=new TreeSet<>(); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); for(Student s:ts){ System.out.println(s.getName()+s.getAge()+"岁"); } }}
比较器排序Comparator
package Set925.ComparatorDemo;public class Student { private String name; private int chinese; private int math; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getChinese() { return chinese; } public void setChinese(int chinese) { this.chinese = chinese; } public int getMath() { return math; } public void setMath(int math) { this.math = math; } public Student(String name, int chinese, int math) { this.name = name; this.chinese = chinese; this.math = math; } public Student() { } public int getSum(){ return chinese+math; }}
package Set925.ComparatorDemo;import java.util.Comparator;import java.util.TreeSet;public class Test { public static void main(String[] args) { TreeSet<Student> ts=new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { int num=o1.getSum()-o2.getSum(); int num2=num==0?o1.getName().compareTo(o2.getName()):num; return num2; } }); Student s1=new Student("wangzhaojun",99,98); Student s2=new Student("diaochan",98,99); Student s3=new Student("xishi",95,96); Student s4=new Student("yangyuhuan",100,97); Student s5=new Student("xiaoqiao",96,99); ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); for(Student s:ts){ System.out.println(s.getName()+":"+s.getChinese()+":"+s.getMath()+":"+s.getSum()); } }}
在TreeSet集合中熟练Comparable和Comparator方法。
|