您的位置:首页 > 编程语言 > Java开发

java 基于comparator的比较器

2012-03-16 21:29 281 查看
import java.util.Comparator;
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){
if(stu.name.equals(this.name)&&stu.age==this.age){
return true;
}else {
return false;
}
}

}
public String toString(){
return name+"\t\t"+age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = 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 comparatotdemo {
public static void main(String[] args) {
Student stu[]={
new Student("Lisi",20),
new Student("zs",22),
new Student("ww",20),
new Student("zl",20),
new Student("sq",22)
};
java.util.Arrays.sort(stu,new StudentComparator());
for(int i=0;i<stu.length;i++){
System.out.println(stu[i]);
}
}
}


与Comparable接口相比,明显Comparator是一种补救 的方法,所以,Comparable接口明显比Comparator方便。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: