[英]What data structure to use?
我需要表示以下数据(在Java中):
我在考虑使用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
包装在一个类中,以便在days
对CRUD操作进行仲裁。 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.