比较器Comparable(内部比较器)和Comparator(外部比较器)
生活随笔
收集整理的這篇文章主要介紹了
比较器Comparable(内部比较器)和Comparator(外部比较器)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
比較器Comparable(內部比較器)和Comparator(外部比較器)
1.使用Comparable是從實體類中直接繼承Comparable接口,并且重寫compareTo方法。
2.使用Comparator是建立一個外部類(繼承Comparator接口,重寫compare方法),在排序時,調用這個外部類,不需要改變之前的實體類
上代碼:
內部比較器:
package comparator;public class Person implements Comparable { //內部比較器private String name;private Integer age;private String sex;public Person(String name, Integer age, String sex) {this.name = name;this.age = age;this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +", sex='" + sex + '\'' +'}';}@Overridepublic int compareTo(Object o) {Person p = (Person) o;int result = this.age>p.age? -1:(this.age==p.age?0:1); //降序排列return result;} }main中實現:
Person p1 = new Person("zs",12,"男");Person p2 = new Person("ls",15,"男");Person p3 = new Person("ww",10,"男");List<Person> list = new ArrayList<>();list.add(p1);list.add(p2);list.add(p3);Collections.sort(list);System.out.println(list);結果:
外部比較器:
實體類:
package comparator;public class Student {private String name;private Integer age;private String sex;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", sex='" + sex + '\'' +'}';}public Student(String name, Integer age, String sex) {this.name = name;this.age = age;this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;} }調用的外部類:
package comparator;import java.util.Comparator;public class OutComparable implements Comparator {@Overridepublic int compare(Object o1, Object o2) {Student p1 = (Student) o1;Student p2 = (Student) o2;return p1.getAge()-p2.getAge();} //外部比較器 }main方法:
Student s1 = new Student("zs",15,"女");Student s2 = new Student("zs",13,"女");Student s3 = new Student("zs",18,"女");List<Student> list1 = new ArrayList<>();list1.add(s1);list1.add(s2);list1.add(s3);Collections.sort(list1,new OutComparable());System.out.println(list1);結果:
【注】
在內部排序中,三元表達式中,返回值-1,此元素要排在之前元素的前面,返回值0,兩個元素并列,返回值1,此元素要排在之前元素的后面。
總結
以上是生活随笔為你收集整理的比较器Comparable(内部比较器)和Comparator(外部比较器)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: for-each的使用
- 下一篇: JDK注解(内置和自定义)