今天寫Android應用,遇到一個對List進行排序的問題,通過google的提示,發現用Collections.sort(List list, Comparator c) 就能夠對List/ArrayList進行排序,很Happy的去寫代碼作測試,結果發現排序沒有起做用,檢查之,發現代碼沒什麼問題啊(代碼以下),奇怪了。
app
- public void changeSort(int type){
- Comparator<ItemBean> comparator;
- Toast.makeText(this, "type=="+type, 5).show();
- switch(type){
- case 1:{
- // 價格從低到高排序
- comparator = new PriceLowToHighComparator();
- Collections.sort(list, comparator);
- }
- break;
- case 2:{
- // 價格從高到低排序
- comparator = new PriceHighToLowComparator();
- Collections.sort(list, comparator);
- }
- break;
- }
- adapter.setItemBeanList(list);
- adapter.notifyDataSetChanged();
- }
- public class PriceHighToLowComparator implements Comparator<ItemBean> {
- @Override
- public int compare(ItemBean itemBean1, ItemBean itemBean2) {
- double price1 = 0;
- double price2 = 0;
- if(itemBean1.getItemPrice() != null && !"".equals(itemBean1.getItemPrice())){
- price1 = Double.parseDouble(itemBean1.getItemPrice());
- }
- if(itemBean2.getItemPrice() != null && !"".equals(itemBean2.getItemPrice())){
- price2 = Double.parseDouble(itemBean2.getItemPrice());
- }
- if(price1 > price2){
- return -1;
- }
- else if(price1 < price2){
- return 1;
- }
- else{
- return 0;
- }
- }
- }
而後就是各類改返回值,反覆改了三次之後發現問題所在,返回值不正確,上面的這個類是list的價格從高到低的規則類,Collections.sort(List list, Comparator c) 會根據返回值來對list中的數據進行排序,最初若是price1>price2,則return 1,可是試驗發現list中的數據無變化,隨後改爲return -1,試驗發現list中的數據能按照預想的效果排序了,但是新的問題出來了,爲何price1>price2,可是要返回-1呢?ide
繼續google之,發現http://solodu.iteye.com/blog/630891 這篇文章的主人在文章結尾說了一段話「要充分理解排序就必須先理解最後的return 0, -1 , 1 這三個數字表明的含義。它們不是表明數字而是表明前面和後面要比較的值哪一個大哪一個小?若是是0表示要比較的這兩個數字相等。若是是1表示前面數字大,若是-1表示前面數字小。要理解這個就沒問題了。」可是結合我本身寫的這個排序規則,我忽然以爲0,1,-1這三個數好像不是說誰大誰小,而是一個排序的問題,當返回-1時,前面的變量(即price1)排在後面的變量(price2)的前面,反之則排在後面。果然如此麼,正好就着此次的項目的排序要求比較多,也就多寫幾個規則測試一下,結果確實如此,根據不一樣規則,若是想將前面的變量放到後面的變量以前,則返回-1便可。測試