¿¹Á¦;
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); // ¹®ÀÚ·Î ºñ±³.
}
} |