Conparable、Conparator
Comparable——可比较的:(定义默认的比较规则)
- 实现该接口表示:这个类的实例可以比较大小,可以进行自然顺序排序
- 定义了默认的比较规则
- 其实现类需要实现compareTo()方法
- compareTo()方法返回正数表示大,负数小,0表示相等
对象的排序:
1 import java.util.*; 2 class ComparableDemo 3 { 4 public static void main(String[] args) 5 { 6 List<student> list = new ArrayList<student>(); 7 8 student [] s = {new student("2","比尔盖茨"),new student("1","乔布斯"),new student("3","图灵")}; 9 list.addAll(Arrays.asList(s)); 10 11 System.out.println("________________排序前___________________"); 12 for (student stu : list) 13 { 14 System.out.println(stu.id+":"+stu.name); 15 } 16 System.out.println("________________排序后___________________"); 17 Collections.sort(list); 18 for (student stu : list) 19 { 20 System.out.println(stu.id+":"+stu.name); 21 } 22 23 } 24 } 25 class student implements Comparable<student>//Comparable接口是带泛型的,实现Comparable接口就必须实现compareTo()方法 26 { 27 String name; 28 String id; 29 student(String id, String name) 30 { 31 this.id = id; 32 this.name = name; 33 } 34 public int compareTo(student o) 35 { 36 //id是一个字符串对象,而字符串对象实现了Comparable接口 37 //此处定义的比较规则为将两个字符串Id的比较规则作为最终结果返回。 38 return this.id.compareTo(o.id); 39 } 40 }
Comparator:(定义临时的比较规则)
- 用于定义临时比较规则,而不是默认比较规则
- 其实现类需要实现compare()方法
Comparator和Comparable都是java集合框架的成员
ComparatorAndComparableDemo:
1 import java.util.*; 2 class ComparatorDemo 3 { 4 public static void main(String[] args) 5 { 6 List<student> list = new ArrayList<student>(); 7 8 student [] s = {new student("2","aaa比尔盖茨"),new student("1","bbb乔布斯"),new student("3","ccc图灵")}; 9 list.addAll(Arrays.asList(s)); 10 11 System.out.println("________________排序前___________________"); 12 for (student stu : list) 13 { 14 System.out.println(stu.id+":"+stu.name); 15 } 16 System.out.println("________________按照ID排序后___________________"); 17 Collections.sort(list); 18 for (student stu : list) 19 { 20 System.out.println(stu.id+":"+stu.name); 21 } 22 System.out.println("________________按姓名排序后___________________"); 23 Collections.sort(list,new studentComparator());//Collections重载的另一个sort()方法 24 for (student stu : list) 25 { 26 System.out.println(stu.id+":"+stu.name); 27 } 28 29 } 30 } 31 class student implements Comparable<student>//Comparable接口是带泛型的,实现Comparable接口就必须实现compareTo()方法 32 { 33 String name; 34 String id; 35 student(String id, String name) 36 { 37 this.id = id; 38 this.name = name; 39 } 40 public int compareTo(student o) 41 { 42 //id是一个字符串对象,而字符串对象实现了Comparable接口 43 //此处定义的比较规则为将两个字符串Id的比较规则作为最终结果返回。 44 return this.id.compareTo(o.id); 45 } 46 } 47 48 //定义一个临时比较规则 49 class studentComparator implements Comparator<student> 50 { 51 //定义了一个临时规则,按照姓名进行排序 52 public int compare(student o1, student o2) 53 { 54 return o1.name.compareTo(o2.name); 55 } 56 }