compareTo 比较器
1 package com.spp.testComparator; 2 3 import java.util.Comparator; 4 5 public class MyComparator implements Comparator { 6 7 @Override 8 public int compare(Object o1, Object o2) { 9 if(null==o1||null==o2){ 10 return -1; 11 } 12 User u1=(User) o1; 13 User u2=(User) o2; 14 if (u1.getAge() > u2.getAge()) { 15 return 1; // 第一个大于第二个 16 } else if (u1.getAge() < u2.getAge()) { 17 return -1;// 第一个小于第二个 18 } else { 19 return 0; // 等于 20 } 21 } 22 23 }
Test.java:
1 package com.spp.testComparator; 2 import java.util.ArrayList; 3 import java.util.Collections; 4 import java.util.List; 5 6 public class Test { 7 8 /** 9 * @param args 10 */ 11 public static void main(String[] args) { 12 // 接口比较器比较,是定义在类的外部的,它不会破坏user2本身 13 List list = new ArrayList(); 14 User u1 = new User(); 15 u1.setName("aaa"); 16 u1.setAge(10); 17 list.add(u1); 18 User u2 = new User(); 19 u2.setName("bbb"); 20 u2.setAge(30); 21 list.add(u2); 22 User u3 = new User(); 23 u3.setName("ccc"); 24 u3.setAge(20); 25 list.add(u3); 26 //之前: 27 for (int i = 0; i < list.size(); i++) { 28 User u = (User) list.get(i); 29 System.out.println("之前:"+u.getAge()); 30 } 31 32 Collections.sort(list, new MyComparator()); 33 34 for (int i = 0; i < list.size(); i++) { 35 User u = (User) list.get(i); 36 System.out.println("之后:"+u.getAge()); 37 } 38 } 39 }
1 package com.spp.testComparator; 2 5 public class User { 6 public String getName() { 7 return name; 8 } 9 public void setName(String name) { 10 this.name = name; 11 } 12 public int getAge() { 13 return age; 14 } 15 public void setAge(int age) { 16 this.age = age; 17 } 18 private String name; 19 private int age; 20 21 }
通过实现Comparator接口,可以实现多种复杂情况的比较