704

Pair<L,R>Javaにない正当な理由はありますか? この C++ 構造に相当するものは何ですか? 自分で再実装するのは避けたいと思います。

1.6も同様のものを提供しているようですが ( ) AbstractMap.SimpleEntry<K,V>、これは非常に複雑に見えます。

4

36 に答える 36

418

のスレッドでcomp.lang.java.help、Hunter Gratzner は、Java に構造体が存在することに反対するいくつかの議論を行っていますPair。主な議論は、クラスPairは 2 つの値の間の関係に関するセマンティクスをまったく伝えないということです (「最初」と「2 番目」の意味をどのように知ることができますか?)。

より良い方法は、Mike が提案したような非常に単純なクラスを作成することです。これは、クラスから作成するアプリケーションごとに作成しますPairMap.Entryは、その名前に意味を持つペアの例です。

要約すると、私の意見では、それが何をすべきかについて何も教えてくれないジェネリックよりも、クラスPosition(x,y)、クラスRange(begin,end)、およびクラスを持つ方が良いと思います。Entry(key,value)Pair(first,second)

于 2008-10-01T08:18:24.500 に答える
162

これはジャバです。説明的なクラス名とフィールド名を使用して、独自に調整された Pair クラスを作成する必要があります。また、hashCode()/equals() を記述したり、Comparable を何度も実装したりすることによって車輪を再発明することを気にしないでください。

于 2010-02-27T10:41:54.187 に答える
58

私が思いつくことができる最短のペアは、Lombokを使用して次のとおりです。

@Data
@AllArgsConstructor(staticName = "of")
public class Pair<F, S> {
    private F first;
    private S second;
}

@arturh からの回答のすべての利点(比較可能性を除く) がありhashCode、、、、および静的な「コンストラクター」があります。equalstoString

于 2010-12-17T14:39:54.383 に答える
40

Apache Commons Lang 3.0+にはいくつかのペアクラスがあります:http: //commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html

于 2012-03-13T00:21:35.360 に答える
32

Pair with を実装する別の方法。

  • public 不変フィールド、つまり単純なデータ構造。
  • 同程度の。
  • 単純なハッシュと等号。
  • シンプルなファクトリなので、型を提供する必要はありません。例: Pair.of("hello", 1);

    public class Pair<FIRST, SECOND> implements Comparable<Pair<FIRST, SECOND>> {
    
        public final FIRST first;
        public final SECOND second;
    
        private Pair(FIRST first, SECOND second) {
            this.first = first;
            this.second = second;
        }
    
        public static <FIRST, SECOND> Pair<FIRST, SECOND> of(FIRST first,
                SECOND second) {
            return new Pair<FIRST, SECOND>(first, second);
        }
    
        @Override
        public int compareTo(Pair<FIRST, SECOND> o) {
            int cmp = compare(first, o.first);
            return cmp == 0 ? compare(second, o.second) : cmp;
        }
    
        // todo move this to a helper class.
        private static int compare(Object o1, Object o2) {
            return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1
                    : ((Comparable) o1).compareTo(o2);
        }
    
        @Override
        public int hashCode() {
            return 31 * hashcode(first) + hashcode(second);
        }
    
        // todo move this to a helper class.
        private static int hashcode(Object o) {
            return o == null ? 0 : o.hashCode();
        }
    
        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof Pair))
                return false;
            if (this == obj)
                return true;
            return equal(first, ((Pair) obj).first)
                    && equal(second, ((Pair) obj).second);
        }
    
        // todo move this to a helper class.
        private boolean equal(Object o1, Object o2) {
            return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2));
        }
    
        @Override
        public String toString() {
            return "(" + first + ", " + second + ')';
        }
    }
    
于 2010-09-05T14:27:25.763 に答える
28

http://www.javatuples.org/index.htmlはどうですか。とても便利です。

javatuples は、1 ~ 10 個の要素のタプル クラスを提供します。

Unit<A> (1 element)
Pair<A,B> (2 elements)
Triplet<A,B,C> (3 elements)
Quartet<A,B,C,D> (4 elements)
Quintet<A,B,C,D,E> (5 elements)
Sextet<A,B,C,D,E,F> (6 elements)
Septet<A,B,C,D,E,F,G> (7 elements)
Octet<A,B,C,D,E,F,G,H> (8 elements)
Ennead<A,B,C,D,E,F,G,H,I> (9 elements)
Decade<A,B,C,D,E,F,G,H,I,J> (10 elements)
于 2012-03-01T19:02:17.057 に答える
13

android はPairクラス ( http://developer.android.com/reference/android/util/Pair.html ) を提供します。ここでは実装:

public class Pair<F, S> {
    public final F first;
    public final S second;

    public Pair(F first, S second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Pair)) {
            return false;
        }
        Pair<?, ?> p = (Pair<?, ?>) o;
        return Objects.equal(p.first, first) && Objects.equal(p.second, second);
    }

    @Override
    public int hashCode() {
        return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
    }

    public static <A, B> Pair <A, B> create(A a, B b) {
        return new Pair<A, B>(a, b);
    }
}
于 2014-05-05T08:45:32.807 に答える
12

何に使いたいかによります。これを行う典型的な理由は、マップを反復処理するためです。そのためには、これを行うだけです (Java 5+):

Map<String, Object> map = ... ; // just an example
for (Map.Entry<String, Object> entry : map.entrySet()) {
  System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue());
}
于 2008-10-01T04:53:59.560 に答える
9

良いニュース JavaFX にはキーと値のペアがあります。

JavaFX を依存関係と import として追加javafx.util.Pairするだけで、C++ のように簡単に使用できます。

Pair <Key, Value> 

例えば

Pair <Integer, Integer> pr = new Pair<Integer, Integer>()

pr.get(key);// will return corresponding value
于 2016-01-24T14:10:35.490 に答える
9

最大の問題は、おそらく、A と B の不変性を保証できないことです (型パラメーターが不変であることを確認する方法を参照)。そのため、たとえば がコレクションに挿入されたhashCode()、同じペアに対して一貫性のない結果が得られる可能性があります (これにより、未定義の動作が発生します)。 、ミュータブル フィールドに関して equals を定義するを参照してください)。特定の (非ジェネリックな) ペア クラスの場合、プログラマは A と B を不変に慎重に選択することで、不変性を確保できます。

とにかく、@PeterLawreyの回答(Java 1.7)からジェネリックの警告をクリアします:

public class Pair<A extends Comparable<? super A>,
                    B extends Comparable<? super B>>
        implements Comparable<Pair<A, B>> {

    public final A first;
    public final B second;

    private Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public static <A extends Comparable<? super A>,
                    B extends Comparable<? super B>>
            Pair<A, B> of(A first, B second) {
        return new Pair<A, B>(first, second);
    }

    @Override
    public int compareTo(Pair<A, B> o) {
        int cmp = o == null ? 1 : (this.first).compareTo(o.first);
        return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
    }

    @Override
    public int hashCode() {
        return 31 * hashcode(first) + hashcode(second);
    }

    // TODO : move this to a helper class.
    private static int hashcode(Object o) {
        return o == null ? 0 : o.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Pair))
            return false;
        if (this == obj)
            return true;
        return equal(first, ((Pair<?, ?>) obj).first)
                && equal(second, ((Pair<?, ?>) obj).second);
    }

    // TODO : move this to a helper class.
    private boolean equal(Object o1, Object o2) {
        return o1 == o2 || (o1 != null && o1.equals(o2));
    }

    @Override
    public String toString() {
        return "(" + first + ", " + second + ')';
    }
}

追加/修正は大歓迎です :) 特に、 の使用についてはよくわかりませんPair<?, ?>

この構文の理由の詳細については、オブジェクトが Comparableを実装することを確認するを参照してください。詳細な説明については、Javaで汎用関数を実装する方法を参照してください。max(Comparable a, Comparable b)

于 2012-12-01T15:37:50.217 に答える
6

Map.Entryインターフェイスは、c++ のペアにかなり近くなります。AbstractMap.SimpleEntryや AbstractMap.SimpleImmutableEntryなどの具体的な実装を見てください。最初の項目は getKey() で、2 番目は getValue() です。

于 2015-05-15T17:36:23.113 に答える
6

私の意見では、Java には Pair はありません。なぜなら、ペアに直接機能を追加したい場合 (Comparable など)、型をバインドする必要があるからです。C++ では気にしません。ペアを構成する型に が含まれていない場合operator <pair::operator <もコンパイルされません。

境界のない Comparable の例:

public class Pair<F, S> implements Comparable<Pair<? extends F, ? extends S>> {
    public final F first;
    public final S second;
    /* ... */
    public int compareTo(Pair<? extends F, ? extends S> that) {
        int cf = compare(first, that.first);
        return cf == 0 ? compare(second, that.second) : cf;
    }
    //Why null is decided to be less than everything?
    private static int compare(Object l, Object r) {
        if (l == null) {
            return r == null ? 0 : -1;
        } else {
            return r == null ? 1 : ((Comparable) (l)).compareTo(r);
        }
    }
}

/* ... */

Pair<Thread, HashMap<String, Integer>> a = /* ... */;
Pair<Thread, HashMap<String, Integer>> b = /* ... */;
//Runtime error here instead of compile error!
System.out.println(a.compareTo(b));

型引数が比較可能かどうかをコンパイル時にチェックする Comparable の例:

public class Pair<
        F extends Comparable<? super F>, 
        S extends Comparable<? super S>
> implements Comparable<Pair<? extends F, ? extends S>> {
    public final F first;
    public final S second;
    /* ... */
    public int compareTo(Pair<? extends F, ? extends S> that) {
        int cf = compare(first, that.first);
        return cf == 0 ? compare(second, that.second) : cf;
    }
    //Why null is decided to be less than everything?
    private static <
            T extends Comparable<? super T>
    > int compare(T l, T r) {
        if (l == null) {
            return r == null ? 0 : -1;
        } else {
            return r == null ? 1 : l.compareTo(r);
        }
    }
}

/* ... */

//Will not compile because Thread is not Comparable<? super Thread>
Pair<Thread, HashMap<String, Integer>> a = /* ... */;
Pair<Thread, HashMap<String, Integer>> b = /* ... */;
System.out.println(a.compareTo(b));

これは良いことですが、今回は Pair の型引数として比較不可能な型を使用することはできません。いくつかのユーティリティ クラスで Pair に多くの Comparator を使用する場合がありますが、C++ のユーザーはそれを理解できない場合があります。別の方法は、型引数に異なる境界を持つ型階層に多くのクラスを記述することですが、可能な境界とそれらの組み合わせが多すぎます...

于 2010-12-15T18:40:08.620 に答える
5

JavaFX (Java 8 にバンドルされています) には Pair< A,B > クラスがあります

于 2015-04-20T23:04:09.280 に答える
5

他の多くの人がすでに述べているように、Pair クラスが役立つかどうかはユースケースに大きく依存します。

プライベート ヘルパー関数の場合、Pair クラスを使用することは完全に正当であり、それによってコードが読みやすくなり、すべてのボイラー プレート コードを使用してさらに別の値クラスを作成する価値がない場合です。

一方、抽象化レベルで、2 つのオブジェクトまたは値を含むクラスのセマンティクスを明確に文書化する必要がある場合は、そのクラスを作成する必要があります。通常、データがビジネス オブジェクトである場合がこれに該当します。

いつものように、熟練した判断が必要です。

2 番目の質問については、Apache Commons ライブラリの Pair クラスをお勧めします。これらは、Java の拡張標準ライブラリと見なされる場合があります。

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html

また、ビジネス オブジェクトの値クラスの記述を簡素化するApache Commons のEqualsBuilderHashCodeBuilder、およびToStringBuilderも参照してください。

于 2011-03-30T16:53:34.827 に答える
5

Java 言語の性質上、人々は実際には を必要としないと思いPairますが、通常はインターフェースが必要です。次に例を示します。

interface Pair<L, R> {
    public L getL();
    public R getR();
}

したがって、2 つの値を返したい場合は、次のようにします。

... //Calcuate the return value
final Integer v1 = result1;
final String v2 = result2;
return new Pair<Integer, String>(){
    Integer getL(){ return v1; }
    String getR(){ return v2; }
}

これは非常に軽量なソリューションであり、「a の意味は何Pair<L,R>ですか?」という質問に答えます。答えは、これは 2 つの (異なる場合もある) 型を持つインターフェイス ビルドであり、それぞれを返すメソッドを持っているということです。さらにセマンティックを追加するのはあなた次第です。たとえば、Position を使用していて、それをコードで本当に示したい場合は、PositionXPositionYを含むを定義IntegerしてPair<PositionX,PositionY>. JSR 308 が利用可能な場合は、それPair<@PositionX Integer, @PositionY Ingeger>を簡素化するために使用することもできます。

編集: ここで指摘しておくべきことの 1 つは、上記の定義が型パラメーター名とメソッド名を明示的に関連付けていることです。Pairこれは、aにはセマンティック情報の欠如があるという主張に対する答えです。実はこのメソッドgetLは「型パラメータ L の型に対応する要素をくれ」という意味で、何か意味があります。

編集: これは、生活を楽にする単純なユーティリティ クラスです。

class Pairs {
    static <L,R> Pair<L,R> makePair(final L l, final R r){
        return new Pair<L,R>(){
            public L getL() { return l; }
            public R getR() { return r; }   
        };
    }
}

利用方法:

return Pairs.makePair(new Integer(100), "123");
于 2012-11-08T23:28:08.737 に答える
4
Collections.singletonMap(left, rigth);
于 2016-02-12T09:16:57.280 に答える
3

簡単な方法 Object [] - 任意の次元のタプルとして使用できます

于 2010-09-29T06:44:19.270 に答える
3

構文は似ていますが、Java と C++ には非常に異なるパラダイムがあります。Java のように C++ を書くのは悪い C++ であり、C++ のように Java を書くのは悪い Java です。

Eclipse のようなリフレクション ベースの IDE を使用すると、「ペア」クラスに必要な機能をすばやく簡単に記述できます。クラスを作成し、2 つのフィールドを定義し、さまざまな [Generate XX] メニュー オプションを使用して、数秒でクラスに入力します。Comparable インターフェイスが必要な場合は、「compareTo」をすばやく入力する必要があるかもしれません。

言語の個別の宣言/定義オプションを使用すると、C++ コード ジェネレーターはあまり良くないため、小さなユーティリティ クラスを手書きするのは、より時間がかかり退屈です。ペアはテンプレートであるため、使用しない関数に料金を支払う必要はなく、typedef 機能により、意味のある型名をコードに割り当てることができるため、「セマンティクスがない」という反対意見は実際には持ちこたえません。

于 2014-02-17T21:19:06.843 に答える
2

たとえば、これは私のコードからのものです。

WeakHashMap<Pair<String, String>, String> map = ...

Haskell の Tuple と同じです。

于 2010-02-03T14:44:10.510 に答える
2

便宜上、複数の程度のタプルを持ついくつかのライブラリを次に示します。

  • Javaタプル。次数 1 ~ 10 のタプルがすべてです。
  • ジャバスラング。次数 0 から 8 までのタプルと、その他の機能的なグッズがたくさんあります。
  • jOOλ。次数 0 ~ 16 のタプルとその他の機能的なグッズ。(免責事項、私はメンテナー会社で働いています)
  • 機能的な Java。次数 0 から 8 までのタプルと、その他の機能的なグッズがたくさんあります。

他のライブラリには、少なくともPairタプルが含まれていると言及されています。

具体的には、(受け入れられた回答で提唱されているように)名目上の型付けではなく、多くの構造的な型付けを利用する関数型プログラミングのコンテキストでは、これらのライブラリとそのタプルは非常に便利です。

于 2015-10-22T13:48:20.667 に答える
2

Java のようなプログラミング言語の場合、ほとんどのプログラマーがペアのようなデータ構造を表すために使用する代替データ構造は 2 つの配列であり、データは同じインデックスを介してアクセスされます。

例: http://www-igm.univ-mlv.fr/~lecroq/string/node8.html#SECTION0080

データを結合する必要があるため、これは理想的ではありませんが、非常に安価であることがわかります。また、ユースケースで座標を保存する必要がある場合は、独自のデータ構造を構築することをお勧めします。

図書館にこんなのあった

public class Pair<First,Second>{.. }
于 2013-03-18T02:40:25.577 に答える
1

非常にシンプルで使いやすいバージョンが必要な場合は、https://github.com/lfac-pt/Java-Pairで入手できるようにしました。また、改善は大歓迎です!

于 2012-01-05T22:22:57.483 に答える
1

com.sun.tools.javac.util.Pair は、ペアの単純な実装です。jdk1.7.0_51\lib\tools.jar にあります。

org.apache.commons.lang3.tuple.Pair 以外は、単なるインターフェースではありません。

于 2014-05-05T08:46:49.263 に答える
1

2 つの値の順序を意味するすべての Pair 実装がここに散らばっていることに気付きました。ペアというと、2 つのアイテムの組み合わせを思い浮かべますが、2 つのアイテムの順序は重要ではありません。hashCodeこれは、コレクションで目的の動作を保証するためのとequalsのオーバーライドを使用した、順序付けられていないペアの実装です。クローンも可能。

/**
 * The class <code>Pair</code> models a container for two objects wherein the
 * object order is of no consequence for equality and hashing. An example of
 * using Pair would be as the return type for a method that needs to return two
 * related objects. Another good use is as entries in a Set or keys in a Map
 * when only the unordered combination of two objects is of interest.<p>
 * The term "object" as being a one of a Pair can be loosely interpreted. A
 * Pair may have one or two <code>null</code> entries as values. Both values
 * may also be the same object.<p>
 * Mind that the order of the type parameters T and U is of no importance. A
 * Pair&lt;T, U> can still return <code>true</code> for method <code>equals</code>
 * called with a Pair&lt;U, T> argument.<p>
 * Instances of this class are immutable, but the provided values might not be.
 * This means the consistency of equality checks and the hash code is only as
 * strong as that of the value types.<p>
 */
public class Pair<T, U> implements Cloneable {

    /**
     * One of the two values, for the declared type T.
     */
    private final T object1;
    /**
     * One of the two values, for the declared type U.
     */
    private final U object2;
    private final boolean object1Null;
    private final boolean object2Null;
    private final boolean dualNull;

    /**
     * Constructs a new <code>Pair&lt;T, U&gt;</code> with T object1 and U object2 as
     * its values. The order of the arguments is of no consequence. One or both of
     * the values may be <code>null</code> and both values may be the same object.
     *
     * @param object1 T to serve as one value.
     * @param object2 U to serve as the other value.
     */
    public Pair(T object1, U object2) {

        this.object1 = object1;
        this.object2 = object2;
        object1Null = object1 == null;
        object2Null = object2 == null;
        dualNull = object1Null && object2Null;

    }

    /**
     * Gets the value of this Pair provided as the first argument in the constructor.
     *
     * @return a value of this Pair.
     */
    public T getObject1() {

        return object1;

    }

    /**
     * Gets the value of this Pair provided as the second argument in the constructor.
     *
     * @return a value of this Pair.
     */
    public U getObject2() {

        return object2;

    }

    /**
     * Returns a shallow copy of this Pair. The returned Pair is a new instance
     * created with the same values as this Pair. The values themselves are not
     * cloned.
     *
     * @return a clone of this Pair.
     */
    @Override
    public Pair<T, U> clone() {

        return new Pair<T, U>(object1, object2);

    }

    /**
     * Indicates whether some other object is "equal" to this one.
     * This Pair is considered equal to the object if and only if
     * <ul>
     * <li>the Object argument is not null,
     * <li>the Object argument has a runtime type Pair or a subclass,
     * </ul>
     * AND
     * <ul>
     * <li>the Object argument refers to this pair
     * <li>OR this pair's values are both null and the other pair's values are both null
     * <li>OR this pair has one null value and the other pair has one null value and
     * the remaining non-null values of both pairs are equal
     * <li>OR both pairs have no null values and have value tuples &lt;v1, v2> of
     * this pair and &lt;o1, o2> of the other pair so that at least one of the
     * following statements is true:
     * <ul>
     * <li>v1 equals o1 and v2 equals o2
     * <li>v1 equals o2 and v2 equals o1
     * </ul>
     * </ul>
     * In any other case (such as when this pair has two null parts but the other
     * only one) this method returns false.<p>
     * The type parameters that were used for the other pair are of no importance.
     * A Pair&lt;T, U> can return <code>true</code> for equality testing with
     * a Pair&lt;T, V> even if V is neither a super- nor subtype of U, should
     * the the value equality checks be positive or the U and V type values
     * are both <code>null</code>. Type erasure for parameter types at compile
     * time means that type checks are delegated to calls of the <code>equals</code>
     * methods on the values themselves.
     *
     * @param obj the reference object with which to compare.
     * @return true if the object is a Pair equal to this one.
     */
    @Override
    public boolean equals(Object obj) {

        if(obj == null)
            return false;

        if(this == obj)
            return true;

        if(!(obj instanceof Pair<?, ?>))
            return false;

        final Pair<?, ?> otherPair = (Pair<?, ?>)obj;

        if(dualNull)
            return otherPair.dualNull;

        //After this we're sure at least one part in this is not null

        if(otherPair.dualNull)
            return false;

        //After this we're sure at least one part in obj is not null

        if(object1Null) {
            if(otherPair.object1Null) //Yes: this and other both have non-null part2
                return object2.equals(otherPair.object2);
            else if(otherPair.object2Null) //Yes: this has non-null part2, other has non-null part1
                return object2.equals(otherPair.object1);
            else //Remaining case: other has no non-null parts
                return false;
        } else if(object2Null) {
            if(otherPair.object2Null) //Yes: this and other both have non-null part1
                return object1.equals(otherPair.object1);
            else if(otherPair.object1Null) //Yes: this has non-null part1, other has non-null part2
                return object1.equals(otherPair.object2);
            else //Remaining case: other has no non-null parts
                return false;
        } else {
            //Transitive and symmetric requirements of equals will make sure
            //checking the following cases are sufficient
            if(object1.equals(otherPair.object1))
                return object2.equals(otherPair.object2);
            else if(object1.equals(otherPair.object2))
                return object2.equals(otherPair.object1);
            else
                return false;
        }

    }

    /**
     * Returns a hash code value for the pair. This is calculated as the sum
     * of the hash codes for the two values, wherein a value that is <code>null</code>
     * contributes 0 to the sum. This implementation adheres to the contract for
     * <code>hashCode()</code> as specified for <code>Object()</code>. The returned
     * value hash code consistently remain the same for multiple invocations
     * during an execution of a Java application, unless at least one of the pair
     * values has its hash code changed. That would imply information used for 
     * equals in the changed value(s) has also changed, which would carry that
     * change onto this class' <code>equals</code> implementation.
     *
     * @return a hash code for this Pair.
     */
    @Override
    public int hashCode() {

        int hashCode = object1Null ? 0 : object1.hashCode();
        hashCode += (object2Null ? 0 : object2.hashCode());
        return hashCode;

    }

}

この実装は適切に単体テストされており、Set および Map での使用が試行されています。

これをパブリック ドメインでリリースするとは主張していないことに注意してください。これは私がアプリケーションで使用するために書いたばかりのコードなので、使用する場合は、直接コピーしてコメントや名前を少し変更することは控えてください。私のドリフトをキャッチしますか?

于 2011-04-20T17:53:55.943 に答える
0

多くの人がマップのキーとして使用できるコードを投稿しています...ペアをハッシュキー(一般的なイディオム)として使用しようとしている場合は、Guavaの:httpPair : //code.googleを確認してください。 .com / p / guava-libraries / wiki / NewCollectionTypesExplained#Table。グラフのエッジについて、次の使用例を示します。Table<R,C,V>

Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4);
weightedGraph.put(v1, v3, 20);
weightedGraph.put(v2, v3, 5);

weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20
weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5

は、2つのキーを単一のTable値にマップし、両方のタイプのキーだけでも効率的なルックアップを提供します。Map<Pair<K1,K2>, V>コードの多くの部分ではなく、このデータ構造を使い始めました。独自の中間マップクラスを指定するオプションを使用して、密な用途と疎な用途の両方に対応する配列、ツリー、およびその他の実装があります。

于 2012-12-28T04:40:01.233 に答える
0
public class Pair<K, V> {

    private final K element0;
    private final V element1;

    public static <K, V> Pair<K, V> createPair(K key, V value) {
        return new Pair<K, V>(key, value);
    }

    public Pair(K element0, V element1) {
        this.element0 = element0;
        this.element1 = element1;
    }

    public K getElement0() {
        return element0;
    }

    public V getElement1() {
        return element1;
    }

}

利用方法 :

Pair<Integer, String> pair = Pair.createPair(1, "test");
pair.getElement0();
pair.getElement1();

不変、ペアのみ !

于 2011-12-09T10:55:59.450 に答える
0

VAVR タプルを試してください。

vavr にはタプル型の優れたセットがあるだけでなく、関数型プログラミングも強力にサポートされています。

于 2020-07-08T01:00:13.483 に答える