在哈希表(Java)中,如何找到有多少个键具有相同的值?
让我们说我有:
Hashtable<String, int> table = new Hashtable<String, int>();
table.put("a", 1);
table.put("b", 2);
table.put("c", 2);
table.put("d", 2);
在这种情况下,键:b、c 和 d 将具有相同的值。我怎样才能检测到这一点?
最佳答案
首先,您必须在 Hashtable
定义中使用引用类型(对象)。您不能使用像 int
这样的基本类型,您必须使用 Integer
。
就您的问题而言,您可以使用像这样的小函数来计算某个值在 HashTable
中出现的次数:
int countOccurences(Hashtable<String, Integer> table, int value) {
int count = 0;
for(String key : table.keySet()) {
if(table.get(key) == value) {
count++;
}
}
return count;
}
因此,如果您想知道值 2 在表中出现了多少次:
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
table.put("a", 1);
table.put("b", 2);
table.put("c", 2);
table.put("d", 2);
System.out.println(countOccurences(table, 2));
这将打印 3
关于java - 查找哈希表中有多少个键具有相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25777960/