gpt4 book ai didi

java - 如何比较哈希表中的值或键?

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:58:25 25 4
gpt4 key购买 nike

假设我有代码

public static void main(String args[])
{
Hashtable ht = new Hashtable();
Hashtable ht2 = new Hashtable();
for(int i=0;i<100;i++)
{
ht.put(i, new Integer (i));
}
for(int i=50;i<100;i++)
{
ht2.put(i, new Integer (i));
}
}

如果我想比较两个不同的哈希表,我将如何在 Java 中执行此操作?编辑:如果我想比较哈希表中的键或实际值

最佳答案

这将打印出所有常见的键/值对:

public static void main(String args[])
{
Map<Integer, Integer> ht = new HashMap<Integer, Integer>();
Map<Integer, Integer> ht2 = new HashMap<Integer, Integer>();
for(int i=0;i<100;i++)
{
ht.put(i, i);
}
for(int i=50;i<100;i++)
{
ht2.put(i, i);
}

System.out.println("The following keys and values match:");

for (Map.Entry<Integer, Integer> htEntries : ht.entrySet()) {
if(ht2.containsKey(htEntries.getKey()) && ht2.get(htEntries.getKey()).equals(htEntries.getValue())){
System.out.println("\tKey: " + htEntries.getKey() + " Value: " + htEntries.getValue());
}
}
}

关于java - 如何比较哈希表中的值或键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10127754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com