一、创建Person类
1 public class Person {//应该卸载Test里面 2 private int card ;//身份证号 3 private String name;//姓名 4 private int age;//年龄 5 public Person() { 6 super(); 7 } 8 public Person(int card, String name, int age) { 9 super(); 10 this.card = card; 11 this.name = name; 12 this.age = age; 13 } 14 public int getCard() { 15 return card; 16 } 17 public void setCard(int card) { 18 this.card = card; 19 } 20 public String getName() { 21 return name; 22 } 23 public void setName(String name) { 24 this.name = name; 25 } 26 public int getAge() { 27 return age; 28 } 29 public void setAge(int age) { 30 this.age = age; 31 } 32 @Override 33 public String toString() { 34 return "Person [card=" + card + ", name=" + name + ", age=" + age + "]"; 35 } 36 @Override 37 public int hashCode() { 38 final int prime = 31; 39 int result = 1; 40 result = prime * result + age; 41 result = prime * result + card; 42 result = prime * result + ((name == null) ? 0 : name.hashCode()); 43 return result; 44 } 45 @Override 46 public boolean equals(Object obj) { 47 if (this == obj) 48 return true; 49 if (obj == null) 50 return false; 51 if (getClass() != obj.getClass()) 52 return false; 53 Person other = (Person) obj; 54 if (age != other.age) 55 return false; 56 if (card != other.card) 57 return false; 58 if (name == null) { 59 if (other.name != null) 60 return false; 61 } else if (!name.equals(other.name)) 62 return false; 63 return true; 64 } 65 }
二、创建Test类
1 package HomeWork0607; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.List; 7 8 public class ComparatorTest { 9 public static void main(String[] args) { 10 Person person1 = new Person(1002,"小明",16); 11 Person person2 = new Person(1004,"小红",20); 12 Person person3 = new Person(1006,"小强",18); 13 Person person4 = new Person(1008,"小张",15); 14 List<Person> list = new ArrayList<>(); 15 list.add(person1); 16 list.add(person2); 17 list.add(person3); 18 list.add(person4); 19 System.out.println("排序前:"+list); 20 System.out.println("=======按年龄比较大小======="); 21 Age age = new Age(); 22 Collections.sort(list,age); 23 for (int i = 0; i < list.size(); i++) { 24 System.out.println(list.get(i)); 25 } 26 27 28 System.out.println("======按身份证号比较大小======"); 29 Card card = new Card(); 30 Collections.sort(list,card); 31 for (int i = 0; i < list.size(); i++) { 32 System.out.println(list.get(i)); 33 } 34 35 } 36 } 37 38 39 class Card implements Comparator<Person>{ 40 41 @Override 42 public int compare(Person arg0, Person arg1) { 43 return arg0.getCard()-arg1.getCard();//从小到大排序 44 } 45 } 46 class Age implements Comparator<Person>{ 47 public int compare(Person arg0, Person arg1) { 48 return arg0.getAge()-arg1.getAge();//从小到大排序 49 } 50 }
三、运行截图