簡體   English   中英

在ArrayList的HashTables上執行.contains()

[英]Doing a .contains() on HashTables of ArrayLists

說我有以下兩種結構:

ArrayList<String> test =new ArrayList<String>();
HashTable <ArrayList<String>, Integer> h1 = new Hashtable<Arraylist<String>, Integer>();
HashTable <ArrayList<String>, Integer> h2 = new Hashtable<Arraylist<String>, Integer>();

我可以檢查h1是否包含h2中存在的鍵(基本上是Arraylist),然后按如下所示替換其中的int值:

for (Hashtable <ArrayList<String>, Integer> entry : h2.entrySet()) {
    if(h1.containsKey(entry.getKey()))
    entry.replace(entry.getKey(), 1);
}

或執行:

for (Hashtable <ArrayList<String>, int> entry : h2.entrySet()) {
    if(h1.containsKey(entry.getKey()))
    h2.put(entry.getKey(),1);
}

?? 請幫幫我...

除編譯錯誤外,您的最后一個代碼塊應完全按照您的要求執行。

ArrayList<String> test = new ArrayList<String>();
Hashtable <ArrayList<String>, Integer> h1 = new Hashtable <ArrayList<String>, Integer>();
Hashtable <ArrayList<String>, Integer> h2 = new Hashtable <ArrayList<String>, Integer>();
for (ArrayList<String> key : h2.keySet()) {
    if(h1.containsKey(key))
        h2.put(key, 1);
}

是的,你可以做 因為contains()內部首先執行hashCode()來找出哈希存儲桶。 然后對散列存儲桶中的每個key和傳遞的搜索對象執行equals()

  • equals()ArrayList被覆蓋(通過AbstractList

Javadoc說

此實現首先檢查指定的對象是否是此列表。 如果是這樣,則返回true;否則,返回true。 如果不是,則檢查指定對象是否為列表。 如果不是,則返回false;否則返回false。 如果是這樣,則遍歷兩個列表,比較對應的元素對。 如果有任何比較返回false,則此方法返回false。 如果一個迭代器在另一個迭代器之前用盡了元素,則返回false(因為列表的長度不相等); 否則,在迭代完成時返回true。

換句話說,如果2個列表按相同順序包含相同元素,則它們相等。

  • 並且如果兩個ArrayList具有相同的元素,則它們的hashCode()應該相同

這是一件非常有趣的事情,正如人們已經說過的那樣,您應該認真考慮對數據類型的使用。 但這應該可以解決問題。

Hashtable<ArrayList<String>, Integer> h3 = (Hashtable<ArrayList<String>, Integer>) h2.clone();

for(ArrayList<String> a: h2.keySet()){
    if(h1.containsKey(a)){
        h3.put(a, 1);
    }
}
h2 = h3;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM