Site Search :
Standard Enterprise XML Methodology Pattern Setting Tunning Other
Article Contributors
GuestBook
Javapattern Maven
XSourceGen Dev
JetSpeed Test
JLook Image
jLook Family Site


ComparatorŬ·¡½ºÀÇ °´Ã¼ºñ±³¸¦ ÅëÇÑ sorting
 
ÀϹÝÀûÀ¸·Î primitiveµ¥ÀÌÅÍÇüŸ¦ ÀÌ¿ëÇÏ¿© °´Ã¼¸¦ ºñ±³Çϴ°ÍÀÌ ÀϹÝÀûÀÌÁö¸¸ ±×·¸Áö ¸øÇÒ°æ¿ì°¡ ¸¹´Ù. ±×·² °æ¿ì °´Ã¼¿¡ ´ëÇÑ ºñ±³´Â comparator¸¦ »ç¿ëÇÑ´Ù. ±× »ç¿ë¹ý¿¡ ´ëÇÏ¿© ¾Ë¾Æº»´Ù. ( 2003/02/28 ) 116
Written by ienvyou - ÃÖÁö¿õ
1 of 1
 
¿¹Á¦;

import java.util.*;
public class SortTest 
{
    public static void main(String[] args) throws Exception
    {
        Header [] headers = new Header[10];
        headers[0] = new Header(10, "d");
        headers[1] = new Header(3, "x");
        headers[2] = new Header(6, "y");
        headers[3] = new Header(55, "c");
        headers[4] = new Header(12, "m");
        headers[5] = new Header(21, "t");
        headers[6] = new Header(23, "b");
        headers[7] = new Header(52, "s");
        headers[8] = new Header(8, "r");
        headers[9] = new Header(1, "q ");

        MyComparator comp = new MyComparator();
        comp.setSortMode(2);
        Arrays.sort(headers);
        for(int i = 0 ; i < headers.length ; i++) 
        {
            System.out.println(headers[i]);
        }
    }
}

class MyComparator implements Comparator
{
    private int sortMode; // 1 : msg id sort  2: rchk sort
    public void setSortMode(int sortMode)
    {
        this.sortMode = sortMode;
    }

    public int compare(Object o1, Object o2)
    {
        if( sortMode == 1 )  // MsgId·Î sort(int type)
        {
            if (  ((Header)o1).getMsgId() > ((Header)o2).getMsgId() ) return 1;  
            if (  ((Header)o1).getMsgId() < ((Header)o2).getMsgId() ) return -1;  
            if (  ((Header)o1).getMsgId() == ((Header)o2).getMsgId() ) return 0;
        } else if( sortMode ==2 )  // rChk·Î ¼ÒÆ®(String type)
        {
            return ((Header)o1).getRChk().compareTo(((Header)o2).getRChk() );
        }

        return 0;
    }

    public boolean equals(Object o)
    {
        return (o != null) && (o instanceof Header);   
    }
}

class Header implements Comparable
{
    private int msgId;          
    private String rChk;           
    Header(int msgId, String rChk)
    {
        this.msgId = msgId;
        this.rChk = rChk;
    }
    public String toString() 
    {
        return "msgId : " + msgId + "===rChk : " + rChk;
    }

    public int getMsgId()
    {
        return msgId;
    }
    public String getRChk()
    {
        return rChk;
    }

    public int compareTo(Object obj){
        return this.msgId - ((Header)obj).msgId; // ¼ýÀÚ·Î ºñ±³.
      //  return this.rChk.compareTo(((Header)obj).rChk); // ¹®ÀÚ·Î ºñ±³.
    }

}
 
1
References
 
Copyright ¨Ï 2003 www.javapattern.info & www.jlook.com, an jLOOK co.,LTD