作者:梅爱敏_629 | 来源:互联网 | 2023-10-14 14:58
下面首先我们先创建一个测试类,这里重点说一哈,可以实现一个Comparable接口重写compareTopublicclassTestAimplementsComparable&l
下面首先我们先创建一个测试类,这里重点说一哈,可以实现一个Comparable接口重写compareTo
public class TestA implements Comparable {
private String name;
private Integer age;
public TestA(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "TestA [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(TestA o) {
return this.age.compareTo(o.getAge());
}
}
校验:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class DemoTest {
public static void main(String[] args) {
TestA testA1 = new TestA("老张", 3);
TestA testA2 = new TestA("老李", 1);
TestA testA3 = new TestA("老王", 2);
List list = new ArrayList<>();
list.add(testA1);
list.add(testA2);
list.add(testA3);
System.out.println("排序前--:"+list.toString());
Collections.sort(list, new Comparator() {
@Override
public int compare(TestA o1, TestA o2) {
//升序
return o1.getAge().compareTo(o2.getAge());
}
});
System.out.println("升序排序后--:"+list.toString());
Collections.sort(list, new Comparator() {
@Override
public int compare(TestA o1, TestA o2) {
//降序
return o2.getAge().compareTo(o1.getAge());
}
});
System.out.println("降序排序后--:"+list.toString());
}
}
结果: