how to write write a set for unordered pair in Java

前端 未结 5 1736
夕颜
夕颜 2020-12-31 18:58

I need to have a Set (HashSet) such that if I insert a pair (a, b) and if (b, a) is already in the set, the insertion would just be ignored. How to

5条回答
  •  情话喂你
    2020-12-31 19:08

    Well, it depends on the hashCode() and equals() method of your Pair class. They need to ignore order.

    Set itself is a good example of a class which ignores order for equality--you can look at the code of AbstractSet. If the order of the pair doesn't matter even outside of equality comparison, you can just store HashSets (each with two elements) in your set. It would be best to wrap it in a datatype:

     public class UnorderedPair {
         private final Set set;
    
         public UnorderedPair(T a, T b) {
              set = new HashSet();
              set.add(a);
              set.add(b);
         }
    
         public boolean equals(Object b) {
             //...delegate to set
         }
    
         public int hashCode() {
             return set.hashCode();
         }
    }
    

提交回复
热议问题