【问题标题】:How to sort ArrayList while implementing Parcelable实现 Parcelable 时如何对 ArrayList 进行排序
【发布时间】:2016-03-25 07:33:18
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

  • 您是否尝试过在您的 Categories 类中实现 Comparable? docs.oracle.com/javase/tutorial/collections/interfaces/…
  • @user2004685 我以前从未使用过delegates。你能帮我解决这个问题吗?
  • @user2004685 我不熟悉 Android 编程,但为什么不呢?你能链接一些相关信息吗?
  • @user2004685 上次我读到你可以。你不能扩展一个以上的类,你可以实现很多接口。
  • @RubioRic 是的,你是对的。看来我还在宿醉中。 ;P

标签: java android arraylist


【解决方案1】:

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

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

希望对你有帮助!

【讨论】:

  • 我应该将新的自定义类粘贴到类别类上方吗?
  • 不,只需在另一个文件中创建新类,并在其中对数组进行排序调用Collections.sort(yourListCategories, new CategoriesComparator());
  • 我做了同样的事情,现在它说Cannot resolve sort symbol
【解决方案2】:
Collections.sort(yourListHere,new Comparator<Categories>() {
            @Override
            public int compare(Categories lhs, Categories rhs) {
                //your sort logic here
                return 0;
            }
});

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 2020-03-27
    • 2016-08-28
    • 2011-10-05
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    相关资源
    最近更新 更多