【问题标题】:How to improve this algorithm which fills up a calendar grid?如何改进填充日历网格的算法?
【发布时间】:2010-08-17 13:58:32
【问题描述】:

我有一个可以呈现日历的 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;
}

这让 if 更快,但它仍然太慢。如何改进这个算法?

【问题讨论】:

    标签: java algorithm performance


    【解决方案1】:

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

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

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

    【讨论】:

    • 我还没想过HashMap。我现在就试一试,看看是否真的有帮助。不过,我不想让它太复杂,使用 HashMap 必须是这样的:HashMap&lt;String, ArrayList&lt;Events&gt;&gt;.
    • 我自己多次使用过这种模式。如果您使用的是多线程应用程序,请务必同步所有对 HashMap 的访问以避免冲突。
    【解决方案2】:

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

    如果您有许多多日活动,那么您需要一个间隔树,但将单个活动“五天研讨会”拆分为五个条目“研讨会,五天中的第一天”等可能会更容易。这样就不会发生任何事件从一天到另一天。

    【讨论】:

    • 我已经按照 Erick Robertson 告诉我的方式实现了它。不过,我真的很喜欢你的想法,所以我想我会按照你的建议实施第二个版本。然后我会比较性能并让你知道。谢谢。
    • @Cristian:如果您只需要搜索一天,Erick 的方法至少也能起到同样的效果,如果不是更好的话。但是,如果您需要搜索,比如说,早上,或者一整周,或者其他什么,TreeMap 方法会让事情变得更容易和更一致:只需要求不同的时间间隔,它就会给它给你。
    猜你喜欢
    • 1970-01-01
    • 2011-05-15
    • 2013-01-20
    • 2015-11-19
    • 1970-01-01
    • 2012-01-12
    • 2021-09-11
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多