- 基于
Comparable
的接口类 - 基于
Comparator
的接口类
1、比较器的Comparable
接口类
Comparable
类的定义:
public interface Comparable<T>{ public int compareTo(T o); }
2、Comparable
比较器的返回值:
此方法返回一个int类型的数据,但是此int的值只能是以下三种:
1: 表示大于
-1:表示小于
0: 表示相等
3、Comparable
示例
class Student implements Comparable<Student>{ private String name; private int age; private float score; public Student(String name,int age,float score){ this.name = name; this.age = age; this.score = score; } public String toString(){ return name+"\t\t"+this.age+"\t\t"+this.score; } public int compareTo(Student stu){ if(this.score>stu.score){ return -1; }else if(this.score<stu.score){ return 1; }else{ if(this.age > stu.age){ return 1; }else if(this.age < stu.age){ return -1; }else{ return 0; } } }
}
public class ComparableDemo01{ public static void main(String args[]){ Student stu[] = {new Student("张三",20,99.0f),new Student("李四",22,90.0f),new Student("王五",22,100.0f)}; java.util.Arrays.sort(stu); for(int i=0;i<stu.length;i++){ System.out.println(stu[i]); } }
}
4、比较器的Comparable
接口类
示例
import java.util.* ;
class Student{ private String name ; private int age ; public Student(String name,int age){ this.name = name ; this.age = age ; } public boolean equals(Object obj){ if(this==obj){ return true ; } if(!(obj instanceof Student)){ return false ; } Student stu = (Student) obj ; if(stu.name.equals(this.name)&&stu.age==this.age){ return true ; }else{ return false ; } } public void setName(String name){ this.name = name ; } public void setAge(int age){ this.age = age ; } public String getName(){ return this.name ; } public int getAge(){ return this.age ; } public String toString(){ return name + "\t\t" + this.age ; }
}; class StudentComparator implements Comparator<Student>{ public int compare(Student s1,Student s2){ if(s1.equals(s2)){ return 0 ; }else if(s1.getAge()<s2.getAge()){ return 1 ; }else{ return -1 ; } }
}; public class ComparatorDemo{ public static void main(String args[]){ Student stu[] = {new Student("张三",20), new Student("李四",22),new Student("王五",20), new Student("赵六",20),new Student("孙七",22)} ; java.util.Arrays.sort(stu,new StudentComparator()) ; for(int i=0;i<stu.length;i++){ System.out.println(stu[i]) ; } }
};