日期:2014-05-20  浏览次数:20617 次

不明白对collection排序的问题,希望大家能参与进来,共同讨论,请高手指点
java.util.Comparator接口:
  要实现自己想要的排序方法,要实现此接口.

  int compare(T o1, T o2) ,我一直每搞清楚int型的返回值应该返回什么,返回的数值又是怎么排序的.

  例如:
   
  public class AgreementCoverage {

private String coverageChar;

private String itemCode;


public AgreementCoverage(String coverageChar, String itemCode) {

this.coverageChar = coverageChar;

this.itemCode = itemCode;

}


public String getCoverageChar() {
return coverageChar;
}


public void setCoverageChar(String coverageChar) {
this.coverageChar = coverageChar;
}


public String getItemCode() {
return itemCode;
}


public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}


@Override
public String toString() {
return this.coverageChar + "/" + this.itemCode;
}


public static int compares(int o1, int o2) {
int val1 = o1;
int val2 = o2;
return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1));

}


public static Comparator<AgreementCoverage> getComparator() {

return new Comparator<AgreementCoverage>() {

public int compare(AgreementCoverage o1, AgreementCoverage o2) {

int o1Char = Integer.parseInt(o1.getCoverageChar()), o2Char = Integer
.parseInt(o2.getCoverageChar());
if (o1Char < o2Char) {
return -1;
} else if (o1Char == o2Char)
return 0;
else
return 1;

}
};
}


public static void main(String[] args) {
AgreementCoverage a1 = new AgreementCoverage("0", "63");
AgreementCoverage a2 = new AgreementCoverage("0", "68");
AgreementCoverage a3 = new AgreementCoverage("1", "34");
AgreementCoverage a4 = new AgreementCoverage("0", "52");
AgreementCoverage a5 = new AgreementCoverage("2", "64");
AgreementCoverage a6 = new AgreementCoverage("2", "91");
AgreementCoverage a7 = new AgreementCoverage("2", "90");

List<AgreementCoverage> list = new ArrayList<AgreementCoverage>();
list.add(a1);
list.add(a2);
list.add(a3);
list.add(a4);
list.add(a5);
list.add(a6);
list.add(a7);
Collections.sort(list, AgreementCoverage.getComparator());
for (AgreementCoverage item : list)
System.out.println(item);

}

}

  这是我写的简单的例子,不太明白他为什么就是按这个顺序排列的,请高手能不能给俺讲讲具体是怎么排的?感激不尽!



------解决方案--------------------
Collections.sort()方法对集合进行排序,集合中的任意两个元素的比较依据是把它们传入指定的Comparator的
compare方法,如果返回1,说明第一个元素应该“大于”第二个,应该排在后面。。。
------解决方案--------------------
a > b 返回1
a ==b 返回0
a < b 返回-1

其实,直接返回
a-b 就可以,因为任何正数都代表大于。
------解决方案--------------------
Collections.sort
public static void sort(List list, Comparator c) {
Object a[] = list.toArray();
Arrays.sort(a, c);
ListIterator i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set(a[j]);
}
}

Arrays.mergeSort
/**
* Src is the source array that starts at index 0
* Dest is the (possibly larger) array destination with a possible offset
* low is the index in dest to start sorting
* high is the end index in dest to end sorting
* off is the offset into src corresponding to low in dest