【问题标题】:ArrayList sorting issue in AndroidAndroid中的ArrayList排序问题
【发布时间】:2013-05-09 22:53:37
【问题描述】:

我有一个对象的 ArrayList。

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

我想按数据成员之一的降序对 ArrayList 进行排序,该数据成员是存储为字符串的 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);
    }

}

Item 是一个通用接口:

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>>

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

【问题讨论】:

  • 参考此链接stackoverflow.com/questions/7514451/…> 它将帮助您整理类型数据。
  • 我已经实现了解决方案中提到的相同概念......但是我在这里收到了不同的错误消息
  • 您遇到什么类型的错误?
  • 绑定不匹配:泛型方法 sort(List)... 基本上这就是这里的问题

标签: android sorting arraylist


【解决方案1】:

您的blog_titles 列表是Item 的列表。

Item 本身不是Comparable,而BlogItem 是。

要么将blog_titles 声明为ArrayList&lt;BlogItem&gt;,要么使Item 扩展Comparable

【讨论】:

    【解决方案2】:
    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);
            }
        });
    

    【讨论】:

    • @Sourav 在我的回答中时间戳的数据类型很长。
    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 2019-03-08
    • 2021-06-02
    相关资源
    最近更新 更多