如何在实现 Parcelable 时对 ArrayList 进行排序 [英] How to sort ArrayList while implementing Parcelable

查看:26
本文介绍了如何在实现 Parcelable 时对 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Collections.sort 方法对类别数组列表进行排序,但没有成功.

I am trying to sort the category arraylist with Collections.sort method but have no luck with it.

这是我的代码:

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];
        }
    };
}

推荐答案

您也可以使用自定义比较器:

You can also use custom comparator:

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());

希望能帮到你!

这篇关于如何在实现 Parcelable 时对 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆