java 基于comparator的比较器
2013-07-12 11:25
302 查看
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方便。。。
相关文章推荐
- java 基于comparator的比较器
- JAVA对象比较器Comparator
- Java记录 -61- 比较器Comparator
- JAVA并发编程随笔【三】Comparator接口(类的比较器)
- Java自定义比较器Comparator
- java学习笔记13--比较器(Comparable、Comparator)
- 站稳马步——(3)java比较器——Comparable和Comparator
- java比较器Comparable和Comparator的使用
- JAVA并发编程随笔【三】Comparator接口(类的比较器)
- Java自定义比较器Comparator
- java比较器comparator使用示例分享
- Java中挽救的比较器--Comparator接口
- java比较器Comparator的简单使用
- java学习笔记13--比较器(Comparable、Comparator)
- java中用Comparator比较器对ArrayList排序
- java中的Comparator和Comparable比较器的用法
- java中关于比较器comparator和comparable
- Java中常用的比较器Comparable与Comparator
- Java中容器[Collection(List,Set,Queue),Map],迭代器(Iterator)和比较器(Comparator)及列表排序
- JAVA并发编程随笔【三】Comparator接口(类的比较器)