2

私はintペアを持っています。(整数、整数)

1) k 個のそのようなペアが与えられた場合、それらが一意であるかどうかを確認します。すなわち; k 個のペアから構成される Set のサイズは k ?
2) 指定された k 個のレコードが一意である場合は、それらを並べ替えた順序で格納します (x で競合を解決し、y で解決します)
。 3) サイズ k のそのようなセットが n 個ある場合、セットのセットを作成します。


k = 3 の場合 の要件 1 および 2 の例

(100, 100) (110, 300) (120, 200) は有効なセットであり、ソートされた順序になっています。
(100, 100) (300, 200) (200, 300) は有効なセットですが、ソート順ではありません。
(100, 100) (100, 200) (100, 200) は有効なセットです

要件 3 の
入力例:

(100, 100) (200, 300) (300, 200)
(100, 100) (200, 300) (300, 200)
(100, 100) (201, 300) (300, 200)

出力:

(100, 100) (200, 300) (300, 200)
(100, 100) (201, 300) (300, 200)

これは、私が直面している実際の問題に最も近いアナロジーです。これを Java で行う必要がありますが、Java で作業したことがありません。私は中級の C++ プログラマーです。

醜いコーディングとソートで1と2を解決できました。
ただし、3を取得できません。以下は、これまでに3で取得できたものです。クラスペアは同等のものを実装しています

(ポックコード)

import java.util.HashSet;
public class set {
    public static void main (String []args) {
        HashSet<Pair> s1 = new HashSet();
        s1.add(new Pair(10,10));
        s1.add(new Pair(10,10));

        HashSet<Pair> s2 = new HashSet();
        s2.add(new Pair(10,10));
        s2.add(new Pair(10,10));

        HashSet<HashSet<Pair>> s12 = new HashSet();
        s12.add(s1);s12.add(s2);
        for ( HashSet<Pair> hs : s12) {
            for (Pair p :  hs) {
                System.out.println(""+ p.toString());
            }
        }
    }
}
4

1 に答える 1

2

Pair クラスでequalsand/orメソッドをオーバーライドしなかったようです。hashCode

たとえば、Pairクラスに次の構造がある場合:

protected K value1;
protected V value2; 

equalsand hashCodeas(example)を実装する必要があります:

 public boolean equals(Object obj) {
    if (!(obj instanceof Pair))
        return false;
    Pair that = (Pair)obj;
    boolean result = true;
    if (this.getValue1() != null)
        result = this.getValue1().equals(that.getValue1());
    else if (that.getValue1() != null)
        result = that.getValue1().equals(this.getValue1());

    if (this.getValue2() != null)
        result = result && this.getValue2().equals(that.getValue2());
    else if (that.getValue2() != null)
        result = result && that.getValue2().equals(this.getValue2());

    return result;
} 


public int hashCode() {
    int result = value1 != null ? value1.hashCode() : 0;
    result = 31 * result + (value2 != null ? value2.hashCode() : 0);
    return result;
} 
于 2012-09-02T11:01:18.527 に答える