一个关于Comparator的使用例子

来源:互联网 发布:东京物语 知乎 编辑:程序博客网 时间:2024/05/18 08:42

这两天项目需要用到一个排序,分别对应4个项目,所以写了一个Comparator类。

代码如下:

 import java.util.Comparator;

/**
 * www.webkkk.net
 * @author webkkk
 *
 */
public class TestComparator implements Comparator {

 public int compare(Object arg0, Object arg1) {

  String[] strF = ((String) arg0).split("_");
  String[] strL = ((String) arg1).split("_");
  int len = strF.length;
  if (len == 1) {
   return Integer.parseInt(strF[0]) - Integer.parseInt(strL[0]);
  }
  for (int i = 0; i < len; i++) {
   if (!strF[i].equals(strL[i])) {
    return Integer.parseInt(strF[i]) - Integer.parseInt(strL[i]);
   } else {
    String strNF = getSubValue(strF, i);
    String strNL = getSubValue(strL, i);
    return compare(strNF, strNL);
   }
  }
  return 0;
 }

 public String getSubValue(String[] strObj, int nPast) {
  String strReturn = "";
  for (int i = 1 + nPast; i < strObj.length; i++) {
   strReturn = strReturn + "_" + strObj[i];
  }
  return strReturn.substring(1);
 }
}

然后写一个调用类:

public class Test {
 public static void main(String args[]) throws Exception{
String[] st = {"2_2_107_11","4_1_3_8","1_1_103_3","1_2_103_2","1_1_105_1","2_1_107_5","2_2_107_6","3_1_107_4","2_1_107_10"};
  TestComparator tc = new TestComparator();
  Arrays.sort(st, tc);
  for (int i=0;i < st.length;i ++) {
   System.out.println(st[i]);
  }
 }

 

这个类就算完成了,结果如下:

1_1_103_3
1_1_105_1
1_2_103_2
2_1_107_5
2_1_107_10
2_2_107_6
2_2_107_11
3_1_107_4
4_1_3_8