-4

C++のように使用するために、C++のようにJavaでクラスペアを実現する方法は?

4

3 に答える 3

0

私がそれをしたとき、私はMap.Entry<K, V>標準ライブラリからのインターフェースに似た何かをしました。おそらく and をオーバーライドObject.equals(Object)Object.hashCode()て、キーと値が互いに論理的に等しい 2 つのペアが論理的に等しくなり、同じものをハッシュする必要があります。適切な実装を行う方法については、Bloch の効果的な 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());
}
于 2013-04-04T10:48:39.050 に答える
-1

正しいヘッダーを含めるだけです

#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> = ...
}
于 2013-04-04T11:13:23.887 に答える
-1
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 }
}
于 2013-04-04T10:47:05.013 に答える