[英]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.