Say I have the following ordered pairs (A, B), (A, C), (B, C) and (B, A)
.
Out of those 4 pairs, there are 3 unordered pairs.
My question is: Does java have a data structure that does NOT allow duplicates or palindromes? ((A, B)
and (B, A)
are the same unordered set)
Set
removes the possibility of duplicates, but not the other part.
Set<Entry<Integer, Integer >> values = new HashSet<Entry<Integer, Integer >>();
What data structure is the best choice for this type of thing, or am I better off, just creating my own?
Does java have a data structure that does NOT allow duplicates or palindromes?
Well Java has a number of sets - HashSet
, for example. Those don't allow multiple equal values to be stored... so you just need to create a class which has the sort of equality you want. For example:
// Note: not null-safe. (See below.)
public final class UnorderedPair<T> {
private final T first;
private final T second;
public UnorderedPair(T first, T second) {
this.first = first;
this.second = second;
}
@Override public int hashCode() {
return first.hashCode() + second.hashCode();
}
@Override public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof UnorderedPair)) {
return false;
}
UnorderedPair<?> otherPair = (UnorderedPair<?>) other;
return (first.equals(otherPair.first) && second.equals(otherPair.second))
|| (first.equals(otherPair.second) && second.equals(otherPair.first));
}
public T getFirst() {
return first;
}
public T getSecond() {
return second;
}
}
Then you can just create UnorderedPair<String>
values or whatever, and then a Set<UnorderedPair<String>>
.
Note that the above doesn't handle null values correctly - you'd need to either validate that both first
and second
are non-null in the constructor, or handle possibly-null values.
See more on this question at Stackoverflow