Comparator 和 Comparable 比较

Comparator 是一个比较器,而Comparable是支持排序的一个标识,如果某一个类实现了Comparable则表示类支持排序,且排序方式为‘接口提供’
Comparator是一个比较器, 相当与一个自定义的比较方式,所以不能运用在通用工具中,一般地, 我们使用比较器来比较两个对象的时候,需要借用外部力量,比如内部类实现Comparator,提供compare方法实现。

当我们在后期才会考虑到该类对象需要排序的时候,那么我们可以考虑使用Comparator 自定义个比较器,然后达到排序的目的, 比如String 的忽略大小写比较字符串.

/**
     * A Comparator that orders String objects as by
     * compareToIgnoreCase. This comparator is serializable.
     * 

* Note that this Comparator does not take locale into account, * and will result in an unsatisfactory ordering for certain locales. * The java.text package provides Collators to allow * locale-sensitive ordering. * * @see java.text.Collator#compare(String, String) * @since 1.2 */ public static final Comparator CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator(); private static class CaseInsensitiveComparator implements Comparator, java.io.Serializable { // use serialVersionUID from JDK 1.2.2 for interoperability private static final long serialVersionUID = 8575799808933029326L; public int compare(String s1, String s2) { int n1=s1.length(), n2=s2.length(); for (int i1=0, i2=0; i1compareTo with normalized versions of the strings * where case differences have been eliminated by calling * Character.toLowerCase(Character.toUpperCase(character)) on * each character. *

* Note that this method does not take locale into account, * and will result in an unsatisfactory ordering for certain locales. * The java.text package provides collators to allow * locale-sensitive ordering. * * @param str the String to be compared. * @return a negative integer, zero, or a positive integer as the * specified String is greater than, equal to, or less * than this String, ignoring case considerations. * @see java.text.Collator#compare(String, String) * @since 1.2 */ public int compareToIgnoreCase(String str) { return CASE_INSENSITIVE_ORDER.compare(this, str); }

你可能感兴趣的:(Comparator 和 Comparable 比较)