2014-03-01 29 views
0

我想與一個看似複雜的HashMap對象一起使用來在Android中使我的可展開Listview工作。排序一個完整的HashMap

我的HashMap的通用參數,如下圖所示:

//HashMap<Map<YEAR,MONTH>,List<DAYS>> 
HashMap<Map<Integer,Integer>,List<Integer> 

我使用哈希表來監控日,月,年的時候發生了一件大事。因此,假設在事件發生在12日,20日和25位2013年5月,我會做一些事情,因爲這:

HashMap<Integer,Integer>,List<Integer>> events = new  HashMap<Integer,Integer>,List<Integer>(); 

HashMap<Integer,Integer> yearMonth = new HashMap<Integer,Integer>(); 
yearMonth.put(2013,5); 
events.put(yearMonth,Arrays.asList(new Integer[]{12,20,25})); 

我已經創建了一個適配器,我可擴展列表視圖,如下圖所示它顯示的罰款。現在我希望能夠按年份和月份排序上面的HashMap,以便我的listview將按照2013年,2012年...之後的順序顯示2014年的事件。

這可能嗎?

謝謝。

enter image description here

+0

請繼續閱讀:[http://stackoverflow.com/questions/10456847/sorting-a-arraylisthashmapstring-string-by-a-date-range?rq=1](http://stackoverflow.com/ questions/10456847/sorting-a-arraylisthashmapstring-by-a-date-range?rq = 1) –

+0

你不能像這樣使用HashMap。特別是,使用可變對象(Map)作爲Map的關鍵字將會是災難性的。 –

回答

0

好吧,我剛剛看了 「排序hasmap」。如果你真的想對你的數據進行排序,hashmap肯定是錯誤的。

也許你應該考慮使用一個LinkedList ...

+0

如何表示年份,月份和列表在鏈接列表中的映射?可能嗎?再次感謝。 – nmvictor

+0

直接映射是不可能的,但你可以通過嵌套數據結構來實現。但是,如果這對你很重要,你應該檢查是否有其他字典的實現,然後hashmaps可用(我相信它是) – Anton

0

創建自己的類來代替HashMap中,並調整適配器,以適應這些對象。

然後,您可以實施自己的排序,通過實施可比較並在您的班級中創建compareTo()方法。

這給你所有你需要的控制。例如:

public class myEvent implements Serializable, Comparable<myEvent> 
{ 
    private Integer day; 
    private Integer month; 
    private Integer year; 

    public myEvent(Integer day, Integer month, Integer year, <your other data>) 
    { 
    // Save the stuff here 
    this.day = day; 
    this.month = month; 
    this.year = year; 
    } 

    // Create getDay(), getMonth(), getYear() methods for each parameter 

    public int compareTo(myEvent another) 
    { 
    // Here, compare the two events year by year, month by month, and day by day 
    if (this.year.compareTo(another.getYear()) == 0) 
    { 
     if (this.month.compareTo(another.getMonth()) == 0) 
     { 
      return this.day.compareTo(another.getDay()); 
     } else { 
      return this.month.compareTo(another.getMonth()); 
     } 
    } else { 
     return this.year.compareTo(another.getYear()); 
    } 
    } 

} 

編輯:如果要排序的myEvent對象的列表,你可以使用收藏 API來利用可比執行:

List<myEvent> allevents = new ArrayList<myEvent>(); 
// Add to the list 
... 
// Now sort it. 
Collections.sort(allevents); 

祝你好運。

+0

總是很好,downvote沒有評論。謝謝! – mvreijn