Android中的ArrayList排序问题

时间:2013-05-15 11:29:35

标签: android sorting arraylist

我有一个对象的ArrayList。

ArrayList<Item> blog_titles = new ArrayList<Item>();

我想按照其中一个数据库的降序对ArrayList进行排序,这是一个存储为String的DateTime值(下面代码中的 timestamp )。

public class BlogItem implements Item, Comparable<BlogItem> {

    public final String id;
    public final String heading;
    public final String summary;
    public final String description;
    public final String thumbnail;
    public final String timestamp;  // format:- 2013-02-05T13:18:56-06:00
    public final String blog_link;

    public BlogItem(String id, String heading, String summary, String description, String thumbnail, String timestamp, String blog_link) {      
        this.id = id;
        this.heading = heading;
        this.summary = summary;
        this.description = description;
        this.thumbnail = thumbnail;
        this.timestamp = timestamp;   // format:- 2013-02-05T13:18:56-06:00
        this.blog_link = blog_link;
    }

    @Override
    public int compareTo(BlogItem o) {
        // TODO Auto-generated method stub
        return this.timestamp.compareTo(o.timestamp);
    }

}

项目是通用界面:

public interface Item { 
   // TODO Auto-generated method stub
}

现在我正在尝试对ArrayList进行排序,如:

Collections.sort(blog_titles);

我收到以下错误消息:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (ArrayList<Item>). The inferred type Item is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

如何修复上述错误&amp;这是在这种情况下对ArrayList进行排序的正确方法吗?

2 个答案:

答案 0 :(得分:3)

您的blog_titles列表是Item

的列表

Item本身不是Comparable,而BlogItem是。{/ p>

blog_titles声明为ArrayList<BlogItem>,或将Item声明为Comparable

答案 1 :(得分:1)

Try this..

Collections.sort(blog_titles, new Comparator<BlogItem>() {

        @Override
        public int compare(BlogItem lhs, BlogItem rhs) 
        {
            // TODO Auto-generated method stub
            return (int)(rhs.timestamp - lhs.timestamp);
        }
    });