【发布时间】:2016-12-02 23:03:42
【问题描述】:
Android Studio 在sort() 行中的addAll() 方法内给我一个“API 的使用记录为@since 1.8+”错误。我不太清楚这意味着什么……
我想要做的只是自定义List,我可以通过publishedAt 的Articles_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并具有正常的实现。