【问题标题】:Why is the sort method not working on this custom AbstractList implementation?为什么排序方法不适用于此自定义 AbstractList 实现?
【发布时间】:2016-12-02 23:03:42
【问题描述】:

Android Studio 在sort() 行中的addAll() 方法内给我一个“API 的使用记录为@since 1.8+”错误。我不太清楚这意味着什么……

我想要做的只是自定义List,我可以通过publishedAtArticles_Map 属性对List 进行排序。

AbstractArticlesList

public class AbstractArticlesList extends AbstractList<Articles_Map> {
    private final List<Articles_Map> l;

    public AbstractArticlesList() {
        l = new ArrayList<>();
    }

    public Articles_Map get(int index) {
        return l.get(index);
    }

    public Articles_Map set(int index, Articles_Map element) {
        Articles_Map oldValue = l.get(index);
        l.add(index, element);
        return oldValue;
    }

    public int size() {
        return l.size();
    }

    private void doAdd(Articles_Map another) {
        l.add(another);
    }

    public void addAll(List<Articles_Map> others) {
        for (Articles_Map a : others) {
            doAdd(a);
        }
        l.sort(byPublishedAtComparator);
    }

    private final Comparator<Articles_Map> byPublishedAtComparator =
            new Comparator<Articles_Map>() {
                @Override
                public int compare(Articles_Map o1, Articles_Map o2) {
                    if (o1.publishedAt == null) {
                        return (o2.publishedAt == null) ? 0 : -1;
                    } else if (o2.publishedAt == null) {
                        return 1;
                    }
                    return o1.publishedAt.compareTo(o2.publishedAt);
                }
            };
}

Articles_Map

public class Articles_Map {
    public final String title;
    public final String description;
    public final String url;
    public final String urlToImage;
    public final Date publishedAt;

    public Articles_Map(String title, String description, String url, String urlToImage, Date publishedAt) {
        this.title = title;
        this.description = description;
        this.url = url;
        this.urlToImage = urlToImage;
        this.publishedAt = publishedAt;
    }
}

【问题讨论】:

  • 如果您将 compareFunction 移到内部的 AbstractArticlesList 类中,是否可以完成...?并且可能会在 AbstractArticlesList 类中添加类似的实现。
  • 请注意,自排序 List 违反了 List 合同。确实,这不应该 List,而应该拥有 List 并具有正常的实现。

标签: java android list


【解决方案1】:

sort() is new to API Level 24 (Android 7.0),感谢 Android 开始采用 Java 1.8。

Use Collections.sort() 如果您的 minSdkVersion 小于 24。

【讨论】:

  • 谢谢,这结合 Louis Wasserman 的建议起到了作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 2011-01-26
  • 2020-10-01
  • 1970-01-01
相关资源
最近更新 更多