如何在实现Parcelable时对ArrayList进行排序

时间:2016-03-25 07:33:19

标签: java android arraylist

我正在尝试使用Collections.sort方法对类别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];
        }
    };
}

2 个答案:

答案 0 :(得分:2)

factorCount :: Integral a => a -> a -> a
factorCount n p =
  let (n',r) = n `divMod` p
  in if r == 0 then 1 + factorCount n' p else 0

largest_Power :: Integral a => a -> a -> a
largest_Power n p = sum [ factorCount i p | i <- [1..n] ]

希望这有帮助。

答案 1 :(得分: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());

希望它有所帮助!