黑马程序员------TreeSet的自然排序与比较器

来源:互联网 发布:php7 apache mysql环境 编辑:程序博客网 时间:2024/05/16 10:44

------- android培训、java培训、期待与您交流! ----------

使用TreeSet存储元素,要求元素必须具有"比较的功能"

  我们怎么才能具有比较的功能:

  方式一:将我们的类实现:Comparable接口,重写compareTo()-->自然排序;

  方式二:我们的类不用实现任何接口,在实例化TreeSet时,给TreeSet传递一个"比较器对象",这个比较器对象一定要是:实现Comparator接口,重写compare()方法


使用自然排序:

创建一个自定义类在类中实现comparable接口  重写compareTo方法,这样在向TreeSet中存储元素的时候 会自动调用类的compareto方法进行比较

public class Student implements Comparable {private String name;private int age;public Student(String name, int age) {super();this.name = name;this.age = 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;}@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + "]";}@Overridepublic int compareTo(Object o) {System.out.println("compareTo......");Student stu = (Student)o;//这里是按照字典顺序比较名字字符串如果名字相同在比较年龄 然后返回比较结果int n = this.name.compareTo(stu.getName());int n2 = (n == 0 ? this.age - stu.age : n);//如果name相同,再比较年龄return n2;

使用比较器:

在创建集合的时候为该集合指定一个比较器:

TreeSet<Student> stuSet = new TreeSet<>(new MyComparator());

以下为比较器类:

public class MyComparator<T> implements Comparator<T> {@Overridepublic int compare(T o1, T o2) {System.out.println("MyComparator-->compare()......");//将两个参数转换为StudentStudent stu1 = (Student)o1;Student stu2 = (Student)o2;//先按照字典顺序比较姓名在比较年龄int n = stu1.getName().compareTo(stu2.getName());int n2 = (n == 0 ? stu1.getAge() - stu2.getAge() : n);return n2;}}
为了简化代码,还可以直接在创建集合的时候创建一个匿名内部类的比较器:

TreeSet<Student> ts=new TreeSet<>(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {<span style="white-space:pre"></span>int n = o1.getName().compareTo(o2.getName()); <span style="white-space:pre"></span>int n2=(n==0)?(o1.getAge()-o2.getAge()):
<span style="white-space:pre"></span>n;return n2;}});






0 0
原创粉丝点击