-2

我有一个 HashMap 元素的 ArrayList,其格式为类别、活动和时间。IE

{CATEGORY=Planning, ACTIVITY=Bills, TIME=5}
{CATEGORY=Planning, ACTIVITY=Bills, TIME=7}
{CATEGORY=Planning, ACTIVITY=Meetings, TIME=10}
{CATEGORY=Resources, ACTIVITY=Room1, TIME=15}
....

记下重复的 CATEGORY/ACTIVITY 对,因为这可能在列表中发生

我需要能够将此列表转换为多维列表。对于这个列表的外观,我能想到的最好方法是编写一些伪代码……请在帖子底部查看。

我已经想到了几种不同的方法来实现这一点,但坦率地说,我对如何做到这一点感到困惑和沮丧。我曾考虑过在外部和内部循环中多次循环 ArrayList 的低效方法,但我知道这不是一个好的编码实践。

关于如何实现这种转换的任何建议,以便我可以像下面的伪代码一样循环?

For CATEGORY in CATEGORIES {
    CategoryTime = 0
    Display Category Header
    For ACTIVITY in ACTIVITIES {
        Activity Time = 0
        For TIME_RECORD in ACTIVITY
            Add time to activity total time, category total time & grand total
        }
        Display Activity Total
    }
    Display Category Total
}
Display Grand Total and rest of information...

编辑 我感谢针对此问题提供的所有反馈,看来最好的方法是增强 HashMap 元素的 ArrayList 所属的类。

我已经投票结束这个问题,因为它太本地化了。如果你们中的一些其他开发人员能效仿以结束这个问题,我将不胜感激。我会删除它,但我现在不能,因为有问题的答案。

4

2 回答 2

3

我会写一个看起来像这样的类:

public class Planner  
{    
   Map<Category, Collection<Planner>  details;  
   String activity;  
   long time;  

}  

public enum Category  
{  
    PLANNING,RESOURCES,ETC;  
}    

然后您应该能够执行以下操作:

for(Category current: Planner.getDetails().keySet())  
{  
    CategoryTime = 0  
    Display Category Header
    Activity Time = 0
    for(Planner currentPlanner : planner.getDetails().get(current))  
    {  
          currentPlanner.getActivity();  
          Activity Time += currentPlanner.getTime();
    }  
}  
于 2012-07-16T18:14:53.593 回答
2

使用 Collections API 时会遇到的问题,除了糟糕的抽象之外,还必须Activities为给定的Category. 如果Category是 键,那么您将被迫将 aList<Activity>作为Map. 如果您查询给定的Category,您的工作还没有完成:您必须遍历List<Activity>才能找到您想要的。你怎么知道?

这不是Map; 这是一张多地图。

我同意推荐课程的人。它要好得多,而且工作量也不大。更好的抽象和更多的信息隐藏通常对您和您的客户更好。

public class Activity {
    private Category category;
    private Duration duration; // You want to encapsulate value and units together, right?
    // I can see sequencing information that could be useful.  Your whole Planner seems to be in need of work.
}

I think your idea of time units is poorly done, too. I can't tell if TIME=10 means 10 hours, days, weeks, months, years, decades - you get the point. Units matter a lot, especially in this context. You would not want people to add times together that used different units.

于 2012-07-16T18:19:18.403 回答