如何改进填充日历网格的算法?

时间:2010-08-17 13:58:32

标签: java algorithm performance

我有Grid将呈现日历,并且我提供了一个包含事件的ArrayList<CalendarEventEntity>。这些事件必须在网格中突出显示。

由于我必须自己填充网格,我有类似的东西:

for( loop through the days of the month ){
    Calendar eventDate = event.getDate();
    // look for the events in the calendar that matchs this day
    for(CalendarEventEntity event : events) {
        // if there are events in this specific day
        if( eventDate.get(Calendar.YEAR) == calendarMonth.get(Calendar.YEAR) &&
            eventDate.get(Calendar.MONTH) == calendarMonth.get(Calendar.MONTH) &&
            eventDate.get(Calendar.DAY_OF_MONTH) == dayIndex ) {
            // highlight it!!!
        }
    }

}

这很好用,但速度太慢了。所以我想加快速度!我在内部for之前添加了这个:

// ignore dates which does not make part of this month or year
if( eventDate.get(Calendar.YEAR) < calendarMonth.get(Calendar.YEAR) ||
    eventDate.get(Calendar.MONTH) < calendarMonth.get(Calendar.MONTH) ||
    eventDate.get(Calendar.DAY_OF_MONTH) != DateIdx ) {
    continue;
}

// stop when processing dates which are higher than this month or year
if( eventDate.get(Calendar.YEAR) > calendarMonth.get(Calendar.YEAR) ||
    eventDate.get(Calendar.MONTH) > calendarMonth.get(Calendar.MONTH) 
    || eventDate.get(Calendar.DAY_OF_MONTH) != DateIdx ) {
    break;
}

并且如果速度更快,但它仍然太慢。如何改进此算法?

2 个答案:

答案 0 :(得分:3)

问题是每天你必须搜索在该日期寻找事件的每个事件。您需要找到一种方法,只搜索当天的事件,或者知道当天是否有事件发生。

您应该考虑使用HashMap来存储按日期索引的事件。然后,您可以检查当天是否有HashMap条目。你必须选择一种方式来代表一个足够普遍的日子,用作钥匙。

当您必须深入了解某一特定日期的详细信息并仅显示当天的事件时,这也很方便。每次要查找特定日期的事件时,您都不必搜索所有事件。

答案 1 :(得分:1)

这是一个可以从使用(排序)树中受益的问题的典型示例。 Java在TreeMap中提供了一个。您可以使用subMap方法获取一天开始的活动。 Calendar实现了Comparable,所以它应该可行。 (使用日历条目作为键;从前一天的最后一秒到第二天的第一秒使用subMap来获取当天所有相关事件。)

如果您有许多多日活动,那么您需要一个区间树,但可能更容易将单个活动“五天工作坊”分成五个条目“工作坊,五个第一天”等。所以任何事件都不会从一天蔓延到另一天。