且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Java,如何在不重复比较的情况下将 HashMap 中的每个条目与同一 HashMap 中的每个其他条目进行比较?

更新时间:2023-11-28 16:11:04

如果你不小心,消除重复的成本至少会高于对键进行冗余比较的成本.

If you are not careful, the cost of eliminating duplicates could higher than the cost of redundant comparisons for the keys at least.

您可以使用 System.identityHashCode(x)

for(Map.Entry<Key, Value> entry1: map.entrySet()) {
   Key key1 = entry1.getKey();
   int hash1 = System.identityHashCode(key1);
   Value value1 = entry1.getValue();
   for(Map.Entry<Key, Value> entry2: map.entrySet()) {
       Key key2 = entry2.getKey();
       if (key1 > System.identityHashCode(key2)) continue;

       Value value2 = entry1.getValue();
       // compare value1 and value2;
   }
}