【问题标题】:Android create a collection which automatic sort new item when addAndroid创建一个集合,添加时自动排序新项目
【发布时间】:2023-03-19 07:35:01
【问题描述】:

您好,我有一个型号为TopStory 的安卓应用程序。我想创建一个TopStory(topStories)的集合,它按值(即时间)对项目进行排序,每当添加新项目时。新添加的项目将位于正确的索引处(按值时间排序)(即:创建一个已经排序的集合,以便每当我们添加新项目时,它都会自动插入到正确的位置)

这是我的模型

public class TopStory {
    private int id;
    private String title;
    private String author;
    private int score;
    private JSONArray kids;
    private long time;
    private String url;

    public TopStory() {
    }

    public TopStory(int id, String title, String author, int point, long time,String url) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.score = point;
        this.time = time;
        this.url = url;
    }

我应该使用什么? PriorityQueue, TreeMap,...?如何创建那种类型的集合?非常感谢任何帮助。谢谢。

【问题讨论】:

  • java.util.Collections#binarySearch
  • 你好 binarySearch 是用来搜索值以找到它的索引吗?但我们想创建一个已经排序的集合?
  • 它返回:the non-negative index of the element, or a negative index which is the -index - 1 where the element would be inserted

标签: android sorting collections priority-queue


【解决方案1】:

可以使用TreeMap数据结构http://developer.android.com/reference/java/util/TreeMap.html

了解它如何为您工作,

http://www.java2novice.com/java-collections-and-util/treemap/comparator-user-object/

TreeMap<Empl,String> tm = new TreeMap<Empl, String>(new MyNameComp());

tm.put(new Empl("Ram",3000), "RAM");
tm.put(new Empl("John",6000), "JOHN");
tm.put(new Empl("Crish",2000), "CRISH");
tm.put(new Empl("Tom",2400), "TOM");

Set<Empl> keys = tm.keySet();
for(Empl key:keys){
    System.out.println(key+" ==> "+tm.get(key));
}

【讨论】:

  • 非常感谢,我们能否将 String 参数更改为更适合对象列表的内容(例如模型 topStories 列表)?
【解决方案2】:

如果我没看错你的问题,你有一个对象,并且你想将它排序为基于整数属性的数据结构。在这种情况下,我建议实现二叉树。

【讨论】:

  • 抱歉有点不清楚。我的问题是创建一个已经排序的集合,这样每当我们添加新项目时,它就会自动插入到正确的位置。 binaryTree可以根据索引访问项目吗?
  • 如果你正确地实现了算法,将一个对象插入到二叉树中将会把它放在下一个最大和下一个最小的对象之间,
  • 但问题是 binaryTree 不支持按索引号访问项目(即在 recycleView 中的位置)。我们需要坚持列表
  • 您可以使用迭代器遍历树,直到获得索引号。
  • 但是如果我们在 RecycleView 的适配器中如何访问和索引来检索日期呢? (lilke List.get(position))?
猜你喜欢
  • 2017-07-06
  • 1970-01-01
  • 2015-02-26
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 2022-01-06
  • 2015-01-03
  • 1970-01-01
相关资源
最近更新 更多