How to write a collection for unordered pairs in Java

I need a set (HashSet) so that if I insert a pair (a, b) and if (B, a) is already in the set, the insertion will be ignored How do I do this with Java?

Thank you.

Solution

Well, it depends on the hashcode () and equals () methods of your pair class They need to ignore order

Setting itself is a good example of a class that ignores equality order - you can see the code of abstractset If the order of pairs doesn't matter beyond the equality comparison, you can store only hashsets (each with two elements in your collection) It is best to wrap it in a data type:

public class UnorderedPair<T> {
     private final Set<T> set;

     public UnorderedPair(T a,T b) {
          set = new HashSet<T>();
          set.add(a);
          set.add(b);
     }

     public boolean equals(Object b) {
         //...delegate to set
     }

     public int hashCode() {
         return set.hashCode();
     }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>