Usage of comparator in Java
Speaker: Wang Shaohua QQ Group No.: 483773664
In Java, if you want to sort a collection object or array object, you need to implement the comparator interface to achieve the goal that we want.
Next we simulate the sorting of the Date property in the collection object
First, the entity class
| 123456789101112131415161718192021222324 |
package chapter07_11;public class Person { private int age; private String name; public Person(){} public Person(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
Second, realize comparator interface
| 123456789101112131415 |
public class PersonComparator implements Comparator{ /** * 如果o1小于o2,返回一个负数; * 如果o1大于o2,返回一个正数; * 如果他们相等,则返回0; */ @Override public int compare(Object o1, Object o2) { Person p1 = (Person) o1; Person p2 = (Person) o2; if(p1.getAge()<p2.getAge())return -1; if (p1.getAge()>p2.getAge()) return 1; return 0; }} |
Third, testing
| 123456789101112131415161718192021 |
public class TestSort { public static void main(String[] args) { Person p1 = new Person(28,"zhangsan"); Person p2 = new Person(25,"lisi"); Person p3 = new Person(32, "wangwu"); ArrayList list = new ArrayList(); list.add(p1); list.add(p2); list.add(p3); for(Object object:list ){ Person person = (Person) object; System.out.println(person.getAge()+"--"+person.getName()); } System.out.println("-----------------------------"); Collections.sort(list,new PersonComparator()); for(Object object:list ){ Person person = (Person) object; System.out.println(person.getAge()+
Learn the collection with Mr. Wang (11) Usage of comparator in Java
|