Comparator 接口的使用案例
@Data
public class Test{
private String name;
private Integer age;
private String sex;
public Test(){}
public Test(String name,Integer age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
}
class Demo14{
public void test(Comparator<Test> com){
List<Test> allStus = new ArrayList<>();
allStus.add(new Test("小哈",10,"男"));
allStus.add(new Test("小花",8,"女"));
allStus.add(new Test("小金",7,"男"));
allStus.add(new Test("小蓝",7,"男"));
allStus.add(new Test("小黄",9,"男"));
int size = allStus.size();
Test[] sortTemp = new Test[size];
for(int i = 0; i< sortTemp.length; i++){
sortTemp[i] = allStus.get(i);
}
for(int i = 0;i < sortTemp.length-1;i++){
int index = i;
for(int j = i+1; j < sortTemp.length;j++){
if(com.compare(sortTemp[index],sortTemp[j]) > 0){
index = j;
}
}
if(index != i){
Test stu = sortTemp[index];
sortTemp[index] = sortTemp[i];
sortTemp[i] = stu;
}
}
for(int i = 0; i < sortTemp.length; i++){
System.out.println(sortTemp[i]);
}
}
}
class Demo13 implements Comparator<Test>{
@Override
public int compare(Test o1, Test o2) {
return o2.getAge() - o1.getAge();
}
}
class Demo15 implements Comparator<Test>{
@Override
public int compare(Test o1, Test o2) {
return o1.getAge() - o2.getAge();
}
}
如果一个方法的参数是一个接口该怎么处理?
创建他的实现类的对象进行传入
public static void main(String[] args) {
Demo13 demo13 = new Demo13();
test(demo13);
}
public static void test(Comparator<Test> test){
int i = test.compare(new Test("小哈",10,"男"),
new Test("小黄",9,"男"));
System.out.println(i);
}
|