簡體   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