[英]Sorting a complete HashMap
我正在嘗試使用看似復雜的HashMap對象來在android中化我的可擴展Listview。
我的HashMap的通用參數如下所示:
//HashMap<Map<YEAR,MONTH>,List<DAYS>>
HashMap<Map<Integer,Integer>,List<Integer>
我正在使用哈希圖監視事件發生的日期,月份和年份。 因此,假設在2013年5月12日,20日和25日發生了一次活動,我將采取以下措施:
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進行排序,首先按Year和Month排序,以便我的列表視圖將按頂部順序顯示2014年的事件,然后依次顯示2013年,2012年的事件。
這可能嗎?
謝謝。
好吧,我剛剛讀過“對hasmap進行排序”。 如果您真的想對數據進行排序,那么哈希表肯定是錯誤的。
也許您應該考慮使用鏈表...
創建您自己的類而不是哈希圖,並調整適配器以適合那些對象。
然后,您可以通過實現Comparable並在類中創建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對象的列表進行排序時,可以使用Collection api來利用Comparable實現:
List<myEvent> allevents = new ArrayList<myEvent>();
// Add to the list
...
// Now sort it.
Collections.sort( allevents );
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.