Read Sean

Read me, read Sean.
posts - 508, comments - 655, trackbacks - 9, articles - 4

[Jakarta Commons筆記] Commons Collections - Comparator組

Posted on 2005-08-06 08:40 laogao 閱讀(2579) 評論(4)  編輯  收藏 所屬分類: On Java

 

接下來我們會講到輔助類,首先看Comparator組。

 

ReverseComparator

ComparatorChain

NullComparator

FixedOrderComparator

ComparatorUtils

 

其實Comparator這個概念并不是Commons Collections引入的,在標準的Java Collections API中,已經明確定了一個java.util.Comparator接口,只是有很多人并不了解,Commons Collections也只是擴展了這個接口而已。這個java.util.Comparator定義如下核心方法:

 

public int compare(Object arg0, Object arg1)

 

傳給它兩個對象,它要告訴我們這兩個對象哪一個在特定的語義下更“大”,或者兩者相等。如果arg0 > arg1,返回大于0的整數;如果arg0 = arg1,返回0;如果arg0 < arg2,返回小于0的整數。

 

我們看看Commons Collections給我們提供了哪些Comparator的實現類(都在org.apache.commons.collections.comparators包下面):

 

BooleanComparator – 用于排序一組Boolean對象,指明先true還是先false

ComparableComparator – 用于排序實現了java.lang.Comparable接口的對象(我們常用的Java類如StringIntegerDateDoubleFileCharacter等等都實現了Comparable接口);

ComparatorChain – 定義一組Comparator鏈,鏈中的Comparator對象會被依次執行;

FixedOrderComparator – 用于定義一個特殊的順序,對一組對象按照這樣的自定義順序進行排序;

NullComparator – null值也可參與比較,可以設定為先null或者后null

ReverseComparator – 將原有的Comparator效果反轉;

TransformingComparator – 將一個Comparator裝飾為具有Transformer效果的Comparator

 

// 有關Transformer的內容會在以后的筆記中講到。

 

以上除了ComparatorChain之外,似乎都是實現一些很基本的比較方法,但是當我們用ComparatorChain將一組Comparator串起來之后,就可以實現非常靈活的比較操作。那么這些Comparator在實際代碼中如何使用呢?看例子:

 

/** Issue.java */

 

package sean.study.commons.collections;

 

import org.apache.commons.lang.builder.ToStringBuilder;

import org.apache.commons.lang.builder.ToStringStyle;

 

public class Issue {

   

    private long id;

    private String severity;

    private String owner;

   

    public Issue() {

    }

   

    public Issue(long id, String severity, String owner) {

        this.id = id;

        this.severity = severity;

        this.owner = owner;

    }

   

    public String toString() {

        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)

                .append("id", id)

                .append("severity", severity)

                .append("owner", owner)

                .toString();

    }

 

    public long getId() {

        return id;

    }

 

    public void setId(long id) {

        this.id = id;

    }

 

    public String getOwner() {

        return owner;

    }

 

    public void setOwner(String owner) {

        this.owner = owner;

    }

 

    public String getSeverity() {

        return severity;

    }

 

    public void setSeverity(String severity) {

        this.severity = severity;

    }

 

}

 

/** ComparatorUsage.java */

 

package sean.study.commons.collections;

 

import java.util.Arrays;

import java.util.Comparator;

 

import org.apache.commons.beanutils.BeanComparator;

import org.apache.commons.collections.comparators.ComparatorChain;

import org.apache.commons.collections.comparators.FixedOrderComparator;

import org.apache.commons.lang.StringUtils;

 

public class ComparatorUsage {

 

    public static void main(String[] args) {

        demoComparator();

    }

   

    public static void demoComparator() {

        System.out.println(StringUtils.center(" demoComparator ", 40, "="));

        // data setup

        Issue[] issues = new Issue[] {

                new Issue(15102, "Major", "John"),

                new Issue(15103, "Minor", "Agnes"),

                new Issue(15104, "Critical", "Bill"),

                new Issue(15105, "Major", "John"),

                new Issue(15106, "Major", "John"),

                new Issue(15107, "Critical", "John"),

                new Issue(15108, "Major", "Agnes"),

                new Issue(15109, "Minor", "Julie"),

                new Issue(15110, "Major", "Mary"),

                new Issue(15111, "Enhancement", "Bill"),

                new Issue(15112, "Minor", "Julie"),

                new Issue(15113, "Major", "Julie")

        };

        // comparators setup

        String[] severityOrder = {"Critical", "Major", "Minor", "Enhancement"};

        Comparator severityComparator = new FixedOrderComparator(severityOrder);

        ComparatorChain compChain = new ComparatorChain();

        compChain.addComparator(new BeanComparator("owner"));

        compChain.addComparator(new BeanComparator("severity", severityComparator));

        compChain.addComparator(new BeanComparator("id"));

        // sort and display

        Arrays.sort(issues, compChain);

        for (int i = 0; i < issues.length; i++) {

            System.out.println(issues[i]);

        }

        System.out.println(StringUtils.repeat("=", 40));

    }

   

}

 

輸出結果為:

 

============ demoComparator ============

Issue[id=15108,severity=Major,owner=Agnes]

Issue[id=15103,severity=Minor,owner=Agnes]

Issue[id=15104,severity=Critical,owner=Bill]

Issue[id=15111,severity=Enhancement,owner=Bill]

Issue[id=15107,severity=Critical,owner=John]

Issue[id=15102,severity=Major,owner=John]

Issue[id=15105,severity=Major,owner=John]

Issue[id=15106,severity=Major,owner=John]

Issue[id=15113,severity=Major,owner=Julie]

Issue[id=15109,severity=Minor,owner=Julie]

Issue[id=15112,severity=Minor,owner=Julie]

Issue[id=15110,severity=Major,owner=Mary]

========================================

 

我們可以看到,ComparatorChain中的Comparator被依次執行,先按name,再按我們自定義的severity次序,再按id,最終我們得到了重新排列的數組。

 

 

Feedback

# re: [Jakarta Commons筆記] Commons Collections - Comparator組  回復  更多評論   

2005-08-21 23:12 by 江南白衣[ITO]
ReverseComparator
ComparatorChain
NullComparator

是三個極重要的功能,JDK里面居然不提供標準實現真是太離譜了,幸虧有Commons

# re: [Jakarta Commons筆記] Commons Collections - Comparator組  回復  更多評論   

2006-12-09 01:10 by
Comparable 和 Comparator 知道,Commons做的很漂亮.

# re: [Jakarta Commons筆記] Commons Collections - Comparator組  回復  更多評論   

2007-04-29 16:24 by Thomas Tan
覺得jdk應該是面向所有人的了,而不是只是針對特定的情況設計的了。要想更適合自己的commons,該自己動手!哈

# re: [Jakarta Commons筆記] Commons Collections - Comparator組  回復  更多評論   

2007-04-29 16:26 by Thomas Tan
不過覺得這些commons所設計的,確實讓我們方便和自由選擇多了很多!thx Sean. 收藏了啊!呵呵

只有注冊用戶登錄后才能發表評論。


網站導航:
 
云南11选5软件