java - 用于在 Java 中获取唯一的集合元素对的习惯用法

标签 java collections set

是否有一个标准的习惯用法来获取给定集合中每对唯一元素的集合?

为了我们的目的,(a,b) 的集合等同于 (b,a),因此只有一个应该出现在结果集中。

我可以看到如何使用基于成对元素实现 hashCode 和 equals() 的 Pair 类来构造这样一个集合,但我想知道是否还没有更标准的方法来生成这样一个集合.

最佳答案

就像你说的,一个带有 hashcodeequals 的 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/

相关文章:

java - 查找 Eclipse 项目中使用的未使用的 jar

java - 返回迭代器而不是集合

java - 从java中的结果集中获取随机子集

python - 在 Python 中检索特定的集合元素

java - 如何给jvm设置默认参数?

Java项目查找非限定字符串引用的类--请求评论

java - 选择: but not including :之后 ""(含)内的所有文本

java - 从 Html 字符串建模一个类,实例化该类并从该字符串填充变量,然后从该类返回 html 字符串

c# - 如何使用反射在 IEnumerable<T> 上调用 System.Linq.Enumerable.Count<>?

.NET:在集合上调用 .Add 时出现 ArgumentOutOfRangeException(Pivot 控件出现问题)