Collections.sort() 和 Arrays.sort()方法可以对Object数组进行排序,但是这种方法排序要求对象所在的类必须实现Comparable接口,此接口用于指定排序规则

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HDTV implements Comparable<HDTV> {

    private int size;
    private String brand;

    public HDTV(int size, String brand) {
        this.size = size;
        this.brand = brand;
    }

public int getSize() {
    return size;
}

public void setSize(int size) {
    this.size = size;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}

@Override
public int compareTo(HDTV tv) {
    if (this.getSize() > tv.getSize())
        return 1;
    else if (this.getSize() < tv.getSize())
        return -1;
    else
        return 0;
}

public static void main(String[] args) {
    HDTV tv1 = new HDTV(55, "Samsung");
    HDTV tv2 = new HDTV(60, "Sony");
    HDTV tv3 = new HDTV(35, "Apple");

    List<HDTV> list = new ArrayList<HDTV>();
    list.add(tv1);list.add(tv2);list.add(tv3);

    Collections.sort(list);

    for (HDTV tv : list) {
        System.out.println(tv.getSize()+"---"+tv.getBrand());
    }


}

如果一个类已经开发完成,但是在此类建立的初期并没有实现Comparable接口,此时肯定是无法进行对象排序操作的,所以为了解决这个问题,java定义了另一个比较器的操作接口--Comparator

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class HDTV {
    private int size;
    private String brand;

    public HDTV(int size, String brand) {
        this.size = size;
        this.brand = brand;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }
}

class SizeComparator implements Comparator<HDTV> {
    @Override
    public int compare(HDTV tv1, HDTV tv2) {
        int tv1Size = tv1.getSize();
        int tv2Size = tv2.getSize();

        if (tv1Size > tv2Size) {
            return 1;
        } else if (tv1Size < tv2Size) {
            return -1;
        } else {
            return 0;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        HDTV tv1 = new HDTV(55, "Samsung");
        HDTV tv2 = new HDTV(60, "Sony");
        HDTV tv3 = new HDTV(42, "Panasonic");

    ArrayList<HDTV> al = new ArrayList<HDTV>();
    al.add(tv1);
    al.add(tv2);
    al.add(tv3);

    Collections.sort(al, new SizeComparator());
    for (HDTV a : al) {
        System.out.println(a.getBrand());
    }
}

}

总结:
Comparable 是一个对象本身就已经支持自比较所需要实现的接口(如 String、Integer 自己就可以完成比较大小操作,已经实现了Comparable接口)

用 Comparator 是策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为

参考:Comparable vs Comparator in Java

其他资料:
Comparable与Comparator的区别

Java Sorting: Comparator vs Comparable Tutorial


liujs
277 声望5 粉丝