是否有一个标准的习惯用法来获取给定集合中每对唯一元素的集合?
为了我们的目的,(a,b) 的集合等同于 (b,a),因此只有一个应该出现在结果集中。
我可以看到如何使用基于成对元素实现 hashCode 和 equals() 的 Pair 类来构造这样一个集合,但我想知道是否还没有更标准的方法来生成这样一个集合.
最佳答案
就像你说的,一个带有 hashcode 和 equals 的 Pair 类实现并放置在 HashSet 中将完成你正在寻找的东西。我不知道有 JDK 数据结构可以在本地执行此操作。
如果你想进一步概括它,你可以创建一个元组,Tuple<T1,T2>
并基于该元组声明一个 HashSet,HashSet<Tuple<T1,T2>>
.然后为元组类型创建一个更通用的 Equals/Hashcode 方法。
这是一个示例实现:
final class Pair<A, B> {
private final A _first;
private final B _second;
public Pair(A first, B second) {
_first = first;
_second = second;
}
@Override
public int hashCode() {
int hashFirst = _first != null ? _first.hashCode() : 0;
int hashSecond = _second != null ? _second.hashCode() : 0;
return (hashFirst + hashSecond) * hashSecond + hashFirst;
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return this._first == otherPair._first //
|| (this._first != null //
&& otherPair._first != null && this._first.equals(otherPair._first)) //
&& this._second == otherPair._second //
|| (this._second != null //
&& otherPair._second != null && this._second.equals(otherPair._second));
}
return false;
}
@Override
public String toString() {
return "(" + _first + ", " + _second + ")";
}
public A getFirst() {
return _first;
}
public B getSecond() {
return _second;
}
关于java - 用于在 Java 中获取唯一的集合元素对的习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5428417/