Comparator和Comparable

import java.util.*;

public class TestCollection {
    public static void main(String[] args) {
        Random rd=new Random();
        List<Hero1> all=new ArrayList<>();
        for (int i=0;i<10;i++){
            all.add(new Hero1("hero"+i,rd.nextInt(10),rd.nextInt(10)));
        }
        System.out.println("初始化后:"+all);
        //直接调用sort会出现编译错误,因为Hero1有各种属性
        //到底按照哪种属性进行比较,Collections也不知道,不确定,所以没法排
        //用Comparator,指定比较的算法
        Comparator<Hero1> cp=new Comparator<Hero1>() {
            @Override
            public int compare(Hero1 o1, Hero1 o2) {
                if (o1.save>o2.save)
                    return 1;
                else
                    return -1;
            }
        };
        //指定到底按照哪种属性进行排序
        Collections.sort(all,cp);
        System.out.println("按照save比较后的集合:");
        System.out.println(all);
    }
}
public class Hero1 {
    public String name;
    public int hp;
    public int save;
    public Hero1(String name,int hp,int save){
        this.name=name;
        this.hp=hp;
        this.save=save;
    }

    @Override
    public String toString() {
        return "name:"+this.name+"HP:"+this.hp+"Save:"+this.save;
    }
}

让类实现Comparable接口
在类里面提供比较算法
Collections.sort就有足够的信息进行排序了,也无需额外提供比较器Comparator

public class Hero1 implements Comparable<Hero1> {
    public String name;
    public int hp;
    public int save;
    public Hero1(String name,int hp,int save){
        this.name=name;
        this.hp=hp;
        this.save=save;
    }

    @Override
    public int compareTo(Hero1 o) {
        if (hp<o.hp)
            return 1;
        else
            return -1;
    }

    @Override
    public String toString() {
        return "name:"+this.name+"HP:"+this.hp+"Save:"+this.save;
    }
}
import java.util.*;

public class TestCollection {
    public static void main(String[] args) {
        Random rd=new Random();
        List<Hero1> all=new ArrayList<>();
        for (int i=0;i<10;i++){
            all.add(new Hero1("hero"+i,rd.nextInt(10),rd.nextInt(10)));
        }
        System.out.println("初始化后:"+all);
        //Hero类实现了接口Comparable,即自带比较信息。
        //Collections直接进行排序,无需额外的Comparator
        Collections.sort(all);
        System.out.println("按照hp比较后的集合:");
        System.out.println(all);
    }
}

猜你喜欢

转载自blog.csdn.net/QingXu1234/article/details/81239834
今日推荐