[LIST]ArrayList的自訂排序方法

來源:互聯網
上載者:User
ArrayList的自訂排序方法

Java.util.Collections.sort(List list)與Comparable,Comparator 介面
調用java.util.Collections.sort(List list)方法來進行排序的時候,
List內的Object都必須實現了Comparable介面。
否則出現下面的錯誤:
java.lang.ClassCastException
at java.util.Arrays.mergeSort(Arrays.java:1152)
at java.util.Arrays.sort(Arrays.java:1079)
at java.util.Collections.sort(Collections.java:113)

或者調用
java.util.Collections.sort(List list,Comparator c),
可以臨時聲明一個Comparator 來實現排序。
Comparable介面的 public int compareTo(Object arg0) {]
傳回值大於0,則this被排在後面。arg0放在前面。
可以參看Integer 的compareTo()方法:
public int compareTo(Integer anotherInteger) {
int thisVal = this.value;
int anotherVal = anotherInteger.value;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1)); 根據專家觀察,這樣的理論和現象都是值得各位站長深思的,所以希望大家多做研究學習,爭取總結出更多更好的經驗!
}
傳回值>=0,則不調用Arrays.swap(Object x[], int a, int b) 方法。

通過java.util.Collections.sort(List list,Comparator c)裡臨時聲明的Comparator
可以方便的實現順序或者倒序排列。

樣本如下:

Collections.sort(imageList, new Comparator() {
public int compare(Object a, Object b) {
int orderA = Integer.parseInt( ( (Image) a).getSequence());
int orderB = Integer.parseInt( ( (Image) b).getSequence());
return orderA - orderB;
}
});
如果需要改變排列順序

改成return orderb - orderA 即可。

具體可以參考學習例子有:

http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#sorting
http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorter.java
http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorterDemo.java

這是一個實現了點擊表格標題列來實現表格式資料排序的例子。

ps: Collection(包括ArrayList等)的remove(Object o)方法
(src:java.util.AbstractCollection.java)
if (o.equals(e.next())) { 著作權申明:本站文章均來自網路,本站所有轉載文章言論不代表本站觀點
e.remove();
使用的equals來判斷的,而如果沒有重寫equals方法的話,
實際調用Object的
public boolean equals(Object obj) {
return (this == obj);
}
因此,放進在集合裡的元素,建議都重新實現自己的 equals方法。

如果是int,byte那些是不行的,  
  如果是Object  
  則  
  Arrays.sort(array,   Collections.reverseOrder());

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.