在ArrayLists的HashTables上执行.contains()

时间:2013-07-03 08:32:26

标签: java arraylist replace hashtable

说我有以下两种结构:

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);
}

??请帮帮我...

3 个答案:

答案 0 :(得分:0)

除了编译错误,您的上一个代码块应该完全符合您的要求。

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);
}

答案 1 :(得分:0)

是的,你可以。因为contains()内部首先hashCode()找出哈希桶。然后使用传递的搜索对象对哈希桶中的每个equals()进行key

  • equals()ArrayList(通过AbstractList
  • 中被覆盖

和Javadoc说

  

此实现首先检查指定的对象是否为此列表。   如果是,则返回true;如果没有,它会检查指定的对象是否为a   名单。如果不是,则返回false;如果是这样,它会遍历两个列表,   比较相应的元素对。如果任何比较返回   false,此方法返回false。如果任何迭代器耗尽   另一个元素返回false(如列表所示)   不等长);否则它在迭代时返回true   完整。

换句话说,如果2个列表包含相同序列中的相同元素,则它们是eqaul。

  • 如果两个ArrayList具有相同的元素,则hashCode()应该相同

答案 2 :(得分:0)

这是一个非常奇特的事情,正如人们已经说过的那样,你应该认真考虑使用数据类型。但这应该可以解决问题。

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;
相关问题