【问题标题】:How to implement Pair class in Java like in C++ [duplicate]如何像在 C++ 中一样在 Java 中实现 Pair 类 [重复]
【发布时间】:2013-03-26 09:26:01
【问题描述】:

如何在Java中实现类对,就像在C++中一样,在C++中使用?

【问题讨论】:

  • 在大多数情况下,最好 a) 使用描述两个字段的类,而不仅仅是“left”和“right”,或者 b) 首先避免需要这样的类.

标签: java c++ class std-pair


【解决方案1】:

当我这样做时,我做了一些类似于标准库中的Map.Entry<K, V> 接口的事情。您可能应该覆盖 Object.equals(Object)Object.hashCode() 以便键和值在逻辑上彼此相等的两个对在逻辑上相等并且散列相同 - 请参阅 Bloch 的 Effective Java 的第 9 项以获取有关如何做好实现的一些指针.

这就是我所做的:

@Override
public String toString() {
    //same convention as AbstractMap.SimpleEntry
    return key + "=" + value;
}

@Override
public boolean equals(Object o) {
    if(o == this) return true;
    if(!(o instanceof Pair)) return false;

    Object otherKey = ((Pair<?, ?>)o).getKey();
    Object otherValue = ((Pair<?, ?>)o).getValue();
    return (key == null ? otherKey == null : key.equals(otherKey))
            && (value == null ? otherValue == null
                    : value.equals(otherValue));
}

@Override
public int hashCode() {
    return 17 + 55555 * (key == null ? 72 : key.hashCode())
            + 232323 * (value == null ? 73 : value.hashCode());
}

【讨论】:

    【解决方案2】:
    class Pair<F,S> {
        private F first;
        private S second;
    
        public Pair(F first, S second) { 
            this.first = first;
            this.second = second;
        }
    
        public F getFirst() { return first }
        public S getSecond() { return second }
    }
    

    【讨论】:

    • C++ 对模板允许第一个和第二个元素使用不同的类型
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    【解决方案3】:

    你只需要包含正确的标题

    #include <utility>
    #include <string>
    
    using std::string;
    using std::makepair;
    using std::pair;
    
    void foo()
    {
        string hello("Hello");
        float  value(42);
    
        auto p = makepair(hello, value); // or: pair<string, float> = ...
    }
    

    【讨论】:

    • 这在 Java 中是如何工作的?
    猜你喜欢
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 2023-01-16
    • 2012-03-19
    • 2014-11-10
    • 2019-09-28
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多