Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the sort method not working on this custom AbstractList implementation?

Tags:

java

android

list

Android Studio is giving me a "Usage of API documented as @since 1.8+" error on the sort() line, inside the addAll() method. I'm not quite sure what this means...

All I want to do is a custom List where I can sort the List by the publishedAt property of Articles_Map.

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;
    }
}
like image 956
KaiZ Avatar asked Dec 10 '22 14:12

KaiZ


1 Answers

sort() is new to API Level 24 (Android 7.0), courtesy of Android starting to adopt bits of Java 1.8.

Use Collections.sort() if your minSdkVersion is lower than 24.

like image 64
CommonsWare Avatar answered Dec 13 '22 03:12

CommonsWare