Java集合自定义排序的两种方式(Comparable和Comparator)

Java集合自定义排序的两种方式(Comparable和Comparator)

  1. 方式一:实现compare接口的 compareTo() 方法
public class compare implements Comparable {

    private String name;

    private int age;

    public compare(String name,int age){
        this.name = name;
        this.age = 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;
    }

    @Override
    public String toString() {
        return "compare{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        compare S = (compare) o;
        if(this.name.charAt(0) <= S.getName().charAt(0)){
            return -1;
        }else{
            return 1;
        }
    }

    public static void main(String[] args) {
        Set<compare> list = new HashSet<>();
        list.add(new compare("abc",15));
        list.add(new compare("def",17));
        list.add(new compare("bcd",16));
        List<compare> li = new ArrayList<>(list);
        Collections.sort(li);
        Iterator it = li.iterator();
        while(it.hasNext()) {
            compare tmp = (compare)it.next();
            System.out.println(tmp.toString());
        }
    }
}
  1. 方式二:覆盖comparator的compare方法
public class compareTest implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        String s1 = (String)o1;
        String s2 = (String)o2;
        if(s1.charAt(0) < s2.charAt(0)){
            return 1;
        }else{
            return -1;
        }
    }

    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("abc");
        set.add("def");
        set.add("bcd");
        List<String> list = new ArrayList<>(set);
        Collections.sort(list,new compareTest());
        for(String str : list){
            System.out.println(str);
        }
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                if(s1.charAt(0) < s2.charAt(0)){
                    return -1;
                }else{
                    return 1;
                }
            }
        });
        for(String str : list){
            System.out.println(str);
        }
    }
}

你可能感兴趣的:(Java集合自定义排序的两种方式(Comparable和Comparator))