2016-04-25 60 views
-1

時自動分類新項目您好,我有和Android模型TopStory的應用程序。我想創建一個TopStory(topStories)集合,通過值(ie.time)對商品進行排序每當添加新商品時。新添加的項目將在正確的索引(按值時間順序)(即:創建一個已經排序的收集,以便每當我們添加新項目時,它將自動插入到正確的位置)Android創建一個集合,當添加

這是我的模型

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,...?如何創建這種類型的集合?任何幫助非常感謝。謝謝。

+0

看到'java.util.Collections中#binarySearch' – pskink

+0

喜的binarySearch是要使用搜索值來找到它的索引?但我們想創建一個已經排序的集合? –

+0

它返回:'該元素的非負索引,或負索引是-index-1,其中元素將被插入' – pskink

回答

0

如果我正在閱讀你的問題,你有一個對象,並且你想根據整數屬性將它分類到一個數據結構中。在這種情況下,我建議實施一個二叉樹。

+0

抱歉有點不清楚。我的問題是創建一個已經排序的集合,以便每當我們添加新的項目時,它會自動插入到正確的位置。可以使用binaryTree訪問項目基於索引? –

+0

如果你正確地實現了算法,插入一個對象到binaryTree將把它放在下一個最大的和下一個最小的對象之間 –

+0

,但問題是,binaryTree不支持通過索引號訪問項目(即在recycleView中的位置) 。我們需要堅持列表 –

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)); 
} 
+0

非常感謝,我們可以更改字符串參數到它更適合List對象的東西(例如topStories模型列表)? –

相關問題