Collections工具类中的sort方法有两种形式:
(1) sort(List<T> list)
(2) sort(List<T> list, Comparator<? super T> c)
第一种方法中List类型的对象必须实现Comparable接口,此外,List中的元素必须可比较。
我们先定义类
package com.dongye.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author dongyewujiu
* @date 19-1-9
* @description
*/
public class Person implements Comparable {
private String name;
private int 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;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
@Override
public int compareTo(Object o) {
Person person = (Person) o;
if(this.getAge()>person.getAge()){
return 1;
}else if(this.getAge()<person.getAge()){
return -1;
}else{
return 0;
}
}
}
main方法进行sort方法的调用:
public static void main(String[] args) {
Person person1 = new Person("德玛",19);
Person person2 = new Person("索拉卡",16);
Person person3 = new Person("妖姬",17);
List<Person> list = new ArrayList<>();
list.add(person1);
list.add(person2);
list.add(person3);
Collections.sort(list);
for (Person p:list){
System.out.println(p.toString());
}
}
第二种方法的使用事先无需在自定义对象内部实现排序Comparable接口, 可以在外部实现排序接口Comparator :
public static void main(String[] args) {
Person person1 = new Person("德玛",19);
Person person2 = new Person("索拉卡",16);
Person person3 = new Person("妖姬",17);
List<Person> list = new ArrayList<>();
list.add(person1);
list.add(person2);
list.add(person3);
Collections.sort(list, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o1.getAge() < o2.getAge()) {
return -1;
} else {
return 0;
}
}
});
for (Person p:list){
System.out.println(p.toString());
}
}
原文地址:https://www.cnblogs.com/dongyewujiu/p/10246585.html
时间: 2024-10-09 03:52:29