【问题标题】:Creating a smart data structure in Java在 Java 中创建智能数据结构
【发布时间】:2016-11-27 23:43:42
【问题描述】:

所以我试图创建一个基于 AVL 树和哈希表的智能数据结构。

我确定我需要首先检查数据类型将具有哪种实现,具体取决于提供给它的列表的大小。

例如,如果我有一个大小为 1000 的列表 n,它将使用哈希表来实现。对于超过 1000 的任何内容,使用 AVL 树。

代码:

public class SmartULS<K,V> {

protected TreeMap<K,V> tree = new TreeMap<>();
protected AbstractHashMap<K,V> hashMap = new AbstractHashMap<K,V>();

public void setSmartThresholdULS(size){
    int threshold = 1000;
    if (size >= threshold) {
         map = new AbtractMap<K,V>();
    }
    else
         map = new TreeMap<K,V>();

    }
}

现在,我应该编写标准方法,例如

get(SmartULS, Key), add(SmartULS, Key, Value), remove(SmartULS,Key), nextKey(Key), previousKey(Key)等

我真的不知道如何开始这个?我考虑过像这样创建这些方法(用伪编写):

    Algorithm add(SmartULS, Key, Value):
i<- 0
If SmartULS instanceof AbstractHashMap then
For i to SmartULS.size do
        If Key equals to SmartULS[i] then
            SmartULS.get(Key).setValue(Value)
        Else
            SmartULS.add(Key, Value)
Else if SmartULS instanceof TreeMap then
    Entry newAdd equals new MapEntry(Key, Value)
    Position<Entry> p = treeSearch(root( ), Key)

【问题讨论】:

  • 请阅读How to Ask
  • @EngineerDollery 与其发帖,不如帮助那个人。

标签: java class tree hashtable abstract-data-type


【解决方案1】:

你在正确的轨道上,这就是我理解你的问题并实施它的方式:

public class SmartULS<K, V> {

    Map<K,V> map;

    public static final int THRESHOLD = 1000;

    public SmartULS(int size) {
        if(size < THRESHOLD) {
            map = new HashMap();
        } else {
            map = new TreeMap();
        }
    }

    public V get(K key) {
        return map.get(key);
    }

    public V put(K key, V value) {
        return map.put(key, value);
    }

    public V remove(K key) {
        return map.remove(key);
    }
}

根据给定的初始大小,构造函数决定是初始化哈希表还是树。我还添加了 get、put 和 remove 函数,并使用了 Map 的接口函数。

我不明白 nextKey 和 previousKey 函数应该做什么或返回,所以无法帮助。

使用该类的方式如下:

public static void main(String[] args) {

    SmartULS<String, String> smartULS = new SmartULS(952);

    smartULS.put("firstKey",  "firstValue");
    smartULS.put("secondKey",  "secondsValue");

    String value = smartULS.get("firstKey");

    smartULS.remove("secondKey");

}

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 2019-02-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多