【09】ComparableVS Comparator
看着长得就像 比较的方法
1. Comparable 产生于java.lang ,作用是在类设计的初期使用
实现了重载函数 int compareTo(obj)
2.Comparator 产生于java.util ,作用于类设计后 不动源代码,实现的是 比较器
实现的重造函数 int compare(obj1,obj2)
排序出生于Collections。sort(obj,(比较器))
package Concurrency.mid; import leetcoder.ListNode; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; class person implements Comparable<person>{ public String name; public int id; person(String name ,int id ){ this.name = name; this.id =id ; } @Override public int compareTo(person other){ return this.id < other.id ? -1:1; } @Override public String toString(){ return "name "+ this.name+" id "+id; } } class student{ public String name; public int id; student(String name ,int id ){ this.name = name; this.id =id ; } @Override public String toString(){ return "name "+ this.name+" id "+id; } } class ComparatorStudent implements Comparator<student>{ @Override public int compare(student s1,student s2){ return s1.id < s2.id?-1:1; } } public class compareTest { public static void main(String []arg){ List<person> list= new ArrayList<person>(); list.add(new person("4",4)); list.add(new person("2",2)); list.add(new person("1",1)); list.add(new person("3",3)); System.out.println(list); Collections.sort(list); System.out.println(list); List<student> list2= new ArrayList<>(); list2.add(new student("4",4)); list2.add(new student("2",2)); list2.add(new student("1",1)); list2.add(new student("3",3)); System.out.println(list2); ComparatorStudent comparatorStudent = new ComparatorStudent(); Collections.sort(list2,comparatorStudent); System.out.println(list2); } }
不摸着石头过河,难道要在温柔乡睡到天昏地暗。