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方便。。。
相关文章推荐
- java 基于comparator的比较器
- JAVA并发编程随笔【三】Comparator接口(类的比较器)
- JAVA并发编程随笔【三】Comparator接口(类的比较器)
- java比较器Comparable和Comparator的使用
- Java自定义比较器Comparator
- java比较器Comparator与Comparable
- JAVA对象比较器Comparator
- java比较器comparator使用示例分享
- Java中挽救的比较器--Comparator接口
- java比较器Comparator的简单使用
- java学习笔记13--比较器(Comparable、Comparator)
- java中用Comparator比较器对ArrayList排序
- JAVA并发编程随笔【三】Comparator接口(类的比较器)
- Java记录 -61- 比较器Comparator
- Java中容器[Collection(List,Set,Queue),Map],迭代器(Iterator)和比较器(Comparator)及列表排序
- java积累(一)------后端---Comparator比较器的用法
- JAVA | 35 - 比较器 | Comparator 接口
- JAVA对象比较器Comparator
- Java比较器(Comparable、Comparator)
- JAVA并发编程随笔【三】Comparator接口(类的比较器)