我有两个类型的哈希图A和B。我想同时比较两个映射的值,保持B的值作为比较的参考,如果发现值相等,则递增correctValueCount计数器,否则递增不正确的值计数器。
例如,
int correctValuesCounter = 0;
int incorrectValuesCounter = 0;
Map<Int, Double> A = new HashMap<Int, Double>();
Map<Int, Double> B = new HashMap<Int, Double>();
A.put(1, 0.0);
A.put(2, 1.0);
A.put(3, 0.0);
A.put(4, 0.0);
A.put(5, 1.0);
A.put(6, 1.0);
B.put(1, 0.0);
B.put(2, 1.0);
B.put(3, 0.0);
B.put(4, 0.0);
B.put(5, 1.0);
B.put(6, 1.0);
现在,这些映射值是相等的,因此,correctValuesCounter应该为6,而不正确的ValuesCounter应该为0。类似地,如果将A.put(3,0.0)更改为A.put(3,1.0),而B(2,1.0)为更改为B(2,0.0),那么correctValuesCounter将变为4,而correctValuesCounter将变为2,依此类推。
到目前为止,我没有得到预期的结果,所以有人可以指导我正确的方向吗?
public void checkEqualValues(Map<Integer, Double> A, Map<Integer, Double> B)
{
for(double value : A.values())
{
if(A.size() == B.size())
{
if(B.values().contains(value))
{
correctValuesCounter++;
}
else
incorrectValuesCounter++;
}
else
System.out.println("Unequal list");
}
System.out.println("correctValuesCounter: "+correctValuesCounter);
System.out.println("incorrectValuesCounter:"+incorrectValuesCounter);
}
但是,correctValuesCounter: 6
对于所有排列和组合,这都返回true(即)(即使当我更改两个列表中的值以使彼此不相等时)。有人可以帮忙吗?
您正在将的值与进行比较contains
。
这基本上意味着你增加你的柜台当过一个值B
被包含在A
,如果它涉及到相同的密钥不是!
使用基于键集的迭代来比较值,例如:
if (A.size() != B.size()) {
System.out.println("Different sizes :(");
}
for (Integer key: B.keySet()) {
if (A.get(key) != null && A.get(key).equals(B.get(key))) {
correctValuesCounter++;
}
}
System.out.printf("Correct values counter: %d%n", correctValuesCounter);
输出
Correct values counter: 6
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句