java 基于comparator的比较器

 1 import java.util.Comparator;
2 class Student {
3 private String name;
4 private int age;
5 public Student(String name,int age){
6 this.name=name;
7 this.age=age;
8 }
9 public boolean equals(Object obj){
10 if(this==obj){
11 return true;
12 }
13 if(!(obj instanceof Student)){
14 return false;
15 }
16 Student stu=(Student) obj;
17 if(stu.name.equals(this.name)&&stu.age==this.age){
18 if(stu.name.equals(this.name)&&stu.age==this.age){
19 return true;
20 }else {
21 return false;
22 }
23 }
24
25 }
26 public String toString(){
27 return name+"\t\t"+age;
28 }
29 public String getName() {
30 return name;
31 }
32 public void setName(String name) {
33 this.name = name;
34 }
35 public int getAge() {
36 return age;
37 }
38 public void setAge(int age) {
39 this.age = age;
40 }
41 };
42 class StudentComparator implements Comparator<Student>{
43 public int compare(Student s1,Student s2){
44 if(s1.equals(s2)){
45 return 0;
46 }else if(s1.getAge()<s2.getAge()){
47 return 1;
48 }else {
49 return -1;
50 }
51 }
52 }
53 public class comparatotdemo {
54 public static void main(String[] args) {
55 Student stu[]={
56 new Student("Lisi",20),
57 new Student("zs",22),
58 new Student("ww",20),
59 new Student("zl",20),
60 new Student("sq",22)
61 };
62 java.util.Arrays.sort(stu,new StudentComparator());
63 for(int i=0;i<stu.length;i++){
64 System.out.println(stu[i]);
65 }
66 }
67 }


与Comparable接口相比,明显Comparator是一种补救 的方法,所以,Comparable接口明显比Comparator方便。。。

原文地址:https://www.cnblogs.com/dennisac/p/2400905.html