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!
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).
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.
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.
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 HashSet
s (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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With