繁体   English   中英

使用什么数据结构?

[英]What data structure to use?

我需要表示以下数据(在Java中):

  • 2012年(年)
    • 01(月)
      • 01(日)
        • 你好,我是一个字符串
      • 02
      • ...
    • 02
    • 03
    • 04
    • ...

我在考虑使用TreeMap,但不知道如何使用。 有任何想法吗?

考虑因素,假设您对管理日历条目感兴趣

  • 有无限可能的日期 - 不要在未使用的日子浪费记忆
  • 给定一个日期,您希望快速访问它 - 使用 数组或 基于散列的查找
  • 每一天都有一个独特的日期 - 地图日期=>天

该模型

// best to use ENUM for fixed set of constants
enum Month {
    JANUARY, FEBRUARY, ... , NOVEMBER, DECEMBER
}

enum Weekday {
    SUNDAY, MONDAY, ... , FRIDAY, SATURDAY
}

/**
 * The day "data node". Fill in constructors/accessors.
 */
class Day {
    int year;
    Month month;
    Weekday weekday;
    String date; // hashkey
    String entry; // the entry
}

/**
 * The calendar, simply mapping a unique date to it's day.
 * Create a date like: year + "-" + MONTH + "-" + DAY
 */
HashMap<String, Day> calendar;

风景
由于我们的数据结构不稀疏,因此独立视图必须模拟完整日历。 根据日历规则显示所有日期/生成所有日期,但如果保存新条目,则仅向HashMap添加一天。

笔记

  • 在空间和时间非常有效。
  • 上面的内容过于简化:将HashMap包装在一个类中,以便在daysCRUD操作进行仲裁。
  • 假设你不需要操纵数月/年,而只需要几天。 如果这是错误的,并且您希望例如获得month所有日期,或者删除year ,请考虑使用三年级地图,例如year => month => day以上。

来自Swing的JTree也可以用作数据结构。

但你应该问自己的第一个问题是“我想如何访问数据”。

你需要某种树形结构。 这可能是你的出发点:

public class Node {
    private String label;
    private List<Node> children;
    //add Constructors, getters, setters, and member methods, etc
}


Node root = new Node();
root.setLabel("2012");
//children of root are "01", "02", etc.

绝对独立于视图数据的模型数据。

这是与paislee答案中提出的模型不同的模型。

Map<Calendar, String> thisIsAllYouNeedForTheModel = new HashMap<Calendar, String>();
Calendar thisIsTheKey = Calendar.getInstance();

thisIsTheKey.clear();
thisIsTheKey.set(Calendar.YEAR, theYear);
thisIsTheKey.set(Calendar.MONTH, theMonth);
thisIsTheKey.set(Calendar.DAY_OF_MONTH, theMonth);
thisIsTheKey.set(Calendar.HOUR, theHour);
thisIsTheKey.set(Calendar.MINUTE, theMinute);
thisIsTheKey.set(Calendar.SECOND, theSecond);
thisIsAllYouNeedForTheModel.put(thisIsTheKey, data);

编辑:傻我。 Map<Calendar, String>是我的建议。

我建议使用TreeMap,但是如果你想进行实验,请继续使用LinkedList。 如果遍历许多列表,则访问数据非常复杂。 但实验起来很有趣。

编辑:这是一个教程,包括一个允许您使用TreeMap或类似树的东西的软件包: http//code.google.com/p/qed-java/wiki/HowToUseTree

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM