2016-03-25 66 views
0

我想用Collections.sort方法對類別arraylist進行排序,但沒有運氣。如何在實現Parcelable時排序ArrayList

這裏是我的代碼:

public class Categories implements Parcelable { 
    private ArrayList<Category> category; 
    private Recent recent; 

    public ArrayList<Category> getCategories() { 
     return this.category; 
    } 

    public void setCategory(ArrayList<Category> category) { 
     this.category = category; 
    } 

    public Recent getRecent() { 
     return this.recent; 
    } 

    public void setRecent(Recent recent) { 
     this.recent = recent; 
    } 


    protected Categories(Parcel in) { 
     if (in.readByte() == 0x01) { 
      category = new ArrayList<Category>(); 
      in.readList(category, Category.class.getClassLoader()); 
     } else { 
      category = null; 
     } 
     recent = (Recent) in.readValue(Recent.class.getClassLoader()); 
    } 

    @Override 
    public int describeContents() { 
     return 0; 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     if (category == null) { 
      dest.writeByte((byte) (0x00)); 
     } else { 
      dest.writeByte((byte) (0x01)); 
      dest.writeList(category); 
     } 
     dest.writeValue(recent); 
    } 

    public static final Parcelable.Creator<Categories> CREATOR = new Parcelable.Creator<Categories>() { 
     @Override 
     public Categories createFromParcel(Parcel in) { 
      return new Categories(in); 
     } 

     @Override 
     public Categories[] newArray(int size) { 
      return new Categories[size]; 
     } 
    }; 
} 
+1

你有沒有嘗試在你的類別類實現可比較? https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html – RubioRic

+0

@ user2004685我從來沒有使用'delegates'。你能幫助我嗎? –

+0

@ user2004685我不熟悉Android編程,但爲什麼不呢?你能鏈接一些相關的信息嗎? – RubioRic

回答

2

您還可以使用自定義的比較:

public class CategoriesComparator implements Comparator<Category> { 
    @Override 
    public int compare(Category category1, Category category2) { 
     return category1.getSomeProperty().compareTo(category2.getSomeProperty()); 
    } 
} 

當你想比較稱之爲:

Collections.sort(yourListCategories, new CategoriesComparator()); 

希望它能幫助!

+0

我應該在類別類之上粘貼新的自定義類嗎? –

+0

不,只是在另一個文件中創建新的類,並且你想對你的數組進行排序的位置'Collections.sort(yourListCategories,new CategoriesComparator());' –

+0

我做了同樣的事情,現在它說'無法解析排序符號'。 –

2
Collections.sort(yourListHere,new Comparator<Categories>() { 
      @Override 
      public int compare(Categories lhs, Categories rhs) { 
       //your sort logic here 
       return 0; 
      } 
}); 

希望這有助於。

+0

'無法解析符號排序' –