2015-02-06 68 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>();