Why doesn’t the sorting method work with this custom AbstractList implementation?… here is a solution to the problem.
Why doesn’t the sorting method work with this custom AbstractList implementation?
Android Studio gives 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 that means….
All I want to do is customize the
List, where I can sort the List
by the publishedAt
property of the Articles_Map
List of summary articles:
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);
}
};
}
Article_ 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;
}
}
Solution
sort ()
is new to API Level 24 (Android 7.0), thanks to Android for starting to adopt Java 1.8.
Use Collections.sort()
If your minSdkVersion
is lower than 24.