2015-02-06 118 views
-3

我們可以鏈接散列表中每個鍵的另一個散列表嗎?我們可以把哈希表放在哈希表裏面嗎?

我的目標是有一個非常快速的二維數據結構來存儲電子表格中的單元格。

我會將「行內的所有列」存儲在散列表中。然後對所有'r'行數執行此操作。接下來爲行創建最終的散列表並將所有'r'個散列表存儲在新的散列表中。這種方式有效嗎?或者,還有更好的方法?

+1

你真的嘗試過嗎? :)那你就不用問了。是的,你當然可以做到。 – meskobalazs 2015-02-06 09:31:21

+2

你的意思是像'HashTable >'?是的爲什麼不。 – m0skit0 2015-02-06 09:31:27

+0

我試過了,但它很奏效,但我不確定這是因爲內存浪費而做的那種有效方式。我只是需要你們的建議。 – Malith 2015-02-06 09:40:12

回答

3

如何

Map<String, Map<Integer,Integer>> asdf = new HashMap<String, Map<Integer, Integer>>(); 

但說實話,你應該用它包裝的對象內開始。在這種結構中,全球將非常不方便。

你可以試試這個BiHashMap

public class BiHashMap<K1, K2, V> { 

private final Map<K1, Map<K2, V>> mMap; 

public BiHashMap() { 
    mMap = new HashMap<K1, Map<K2, V>>(); 
} 

/** 
* Associates the specified value with the specified keys in this map (optional operation). If the map previously 
* contained a mapping for the key, the old value is replaced by the specified value. 
* 
* @param key1 
*   the first key 
* @param key2 
*   the second key 
* @param value 
*   the value to be set 
* @return the value previously associated with (key1,key2), or <code>null</code> if none 
* @see Map#put(Object, Object) 
*/ 
public V put(K1 key1, K2 key2, V value) { 
    Map<K2, V> map; 
    if (mMap.containsKey(key1)) { 
     map = mMap.get(key1); 
    } else { 
     map = new HashMap<K2, V>(); 
     mMap.put(key1, map); 
    } 

    return map.put(key2, value); 
} 

/** 
* Returns the value to which the specified key is mapped, or <code>null</code> if this map contains no mapping for 
* the key. 
* 
* @param key1 
*   the first key whose associated value is to be returned 
* @param key2 
*   the second key whose associated value is to be returned 
* @return the value to which the specified key is mapped, or <code>null</code> if this map contains no mapping for 
*   the key 
* @see Map#get(Object) 
*/ 
public V get(K1 key1, K2 key2) { 
    if (mMap.containsKey(key1)) { 
     return mMap.get(key1).get(key2); 
    } else { 
     return null; 
    } 
} 

/** 
* Returns <code>true</code> if this map contains a mapping for the specified key 
* 
* @param key1 
*   the first key whose presence in this map is to be tested 
* @param key2 
*   the second key whose presence in this map is to be tested 
* @return Returns true if this map contains a mapping for the specified key 
* @see Map#containsKey(Object) 
*/ 
public boolean containsKeys(K1 key1, K2 key2) { 
    return mMap.containsKey(key1) && mMap.get(key1).containsKey(key2); 
} 

public void clear() { 
    mMap.clear(); 
} 

} 

然後創建使用它像這樣:

BiHashMap<String,String,String> bigBoard = new BiHashMap<String,String,String>();