Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write write a set for unordered pair in Java

Tags:

java

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 do this in Java?

Many thanks!

like image 805
Qiang Li Avatar asked Jan 18 '12 05:01

Qiang Li


People also ask

What are unordered pairs in sets?

In mathematics, an unordered pair or pair set is a set of the form {a, b}, i.e. a set having two elements a and b with no particular relation between them, where {a, b} = {b, a}. In contrast, an ordered pair (a, b) has a as its first element and b as its second element, which means (a, b) ≠ (b, a).

How do you find unordered pairs in array?

If you are just looking for the number of un-ordered pair and the array is sorted in ascending order. You can use this formula n * (n - 1) / 2. Suppose your array has n elements, for example 3 in your case. It will be 3 * 2 / 2 = 3.

What is unordered pair of vertices?

A graph G is an ordered pair (V, E), where V = V(G) is a set of elements called vertices, E = E(G) is a set of elements called edges, and each edge is an unordered pair of vertices (its ends or end-vertices or end-points). If the two ends are the same, then the edge is called a loop.


1 Answers

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<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();
     }
}
like image 159
Mark Peters Avatar answered Sep 21 '22 16:09

Mark Peters