2013-06-01 35 views
2
if (!mainMethods.matrix.isEmpty()) { 
    for (int i = 0; i < mainMethods.matrix.values().size(); i++) { 
     if (mainMethods.matrix.containsValue(getArrayList()[i].getValue().toString().contains(textValue.getText()))) { 
      String errorTitle = "Impossível completar a operação."; 
      String errorMessage = "Não é possível adicionar um valor de chave repetido."; 
      JOptionPane.showMessageDialog(getParent(), errorMessage, errorTitle, JOptionPane.ERROR_MESSAGE);    
     } 
    } 

這個HashMap叫做「matrix」,它有很多鍵。每個鍵的值都是一個具有自己的值的ArrayList。考慮到這一點,我無法找到一種方法來測試ArrayList-Values中是否存在特定值,因爲如果我將一個String參數傳遞給HashMap的方法「.containsValue()」,該方法將找到一個ArrayList對象和測試將是錯誤的。因此,我必須做一些相當瘋狂的事情,就像我在例子中做的那樣。正如你所看到的,沒有像「getArrayList()」或「getValue()」這樣的東西。這是一個非常複雜的情況,我試圖用「僞碼」來解釋我的觀點。Java - 如何檢查一個ArrayList中的值是否是HashMap中的一個鍵的值?

你知道如何解決它嗎?

+0

我建議你嘗試簡化你的代碼。我並不認爲你真的是要編寫你所寫的代碼。嘗試將代碼分解成更短的代碼行,並查看它們在調試器中的作用。 –

回答

3

如果我理解正確的話,這樣的事情應該工作:

private <K, V> V getValueIfKeyContains(final Map<List<K>, V> map, final K desiredKey) { 
    for (final Entry<List<K>, V> entry : map.entrySet()) { 
     if (entry.getKey().contains(desiredKey)) { 
      return entry.getValue(); 
     } 
    } 
    return null; 
} 

所以你遍歷所有的Map和檢查每個密鑰是否包含desiredKey

強烈建議兩件事情:

  1. 不要使用可變值在Map鍵。這會導致大量問題,因爲他們可以在之後將更改爲Map
  2. 如果您想檢查contains,請勿使用List。這是一個O(n)操作,即它需要與List的大小成比例的時間。它必須遍歷List中的每個元素,直到找到合適的元素。使用Set,操作變爲O(1),即恆定時間。
1

做一件事。改變你的數據結構...

舊之一是:

HashMap <Key, ArrayList> 

更改爲

HashMap<Key, HashMap<Value in ArrayList at index[i], Value in ArrayList at index[i]>>

這假設你在arrayList中有不可變的對象。所以現在一旦你使用鍵獲得一個對象。您可以再次使用密鑰在內部地圖中搜索。

+0

非常有趣!我會盡力去做。 –

1

你可以使用一個迭代器,並檢查每個單獨的數組列表:

Iterator it = mainMethod.matrix.entrySet().iterator(); 
while (it.hasNext()) { 
    Map.Entry pairs = (Map.Entry)it.next(); 
    If(pairs.getValue().contains(your value) 
    { 
     // do stuff 
    } 
} 
0

使用for-each循環遍歷您ArrayList S(我認爲他們持有String S),並使用他們方法來測試一個值內或不存在。

if (!mainMethods.matrix.isEmpty()) { 
    for (List<String> list : mainMethods.matrix.values()) { 
    if (list.contains(textValue.getText())) { 
     String errorTitle="Impossível completar a operação."; 
     String errorMessage="Não é possível adicionar um valor de chave repetido."; 
     JOptionPane.showMessageDialog(
     getParent(), errorMessage, errorTitle, JOptionPane.ERROR_MESSAGE); 
    } 
    } 
} 

如果可能的話切換到使用Set,而不是作爲List搜索一組是快許多倍。但套不會讓你有重複。所以,選擇適合您的需求的更好。

相關問題