Pair<L,R>
Javaにない正当な理由はありますか? この C++ 構造に相当するものは何ですか? 自分で再実装するのは避けたいと思います。
1.6も同様のものを提供しているようですが ( ) AbstractMap.SimpleEntry<K,V>
、これは非常に複雑に見えます。
のスレッドでcomp.lang.java.help
、Hunter Gratzner は、Java に構造体が存在することに反対するいくつかの議論を行っていますPair
。主な議論は、クラスPair
は 2 つの値の間の関係に関するセマンティクスをまったく伝えないということです (「最初」と「2 番目」の意味をどのように知ることができますか?)。
より良い方法は、Mike が提案したような非常に単純なクラスを作成することです。これは、クラスから作成するアプリケーションごとに作成しますPair
。Map.Entry
は、その名前に意味を持つペアの例です。
要約すると、私の意見では、それが何をすべきかについて何も教えてくれないジェネリックよりも、クラスPosition(x,y)
、クラスRange(begin,end)
、およびクラスを持つ方が良いと思います。Entry(key,value)
Pair(first,second)
これはジャバです。説明的なクラス名とフィールド名を使用して、独自に調整された Pair クラスを作成する必要があります。また、hashCode()/equals() を記述したり、Comparable を何度も実装したりすることによって車輪を再発明することを気にしないでください。
私が思いつくことができる最短のペアは、Lombokを使用して次のとおりです。
@Data
@AllArgsConstructor(staticName = "of")
public class Pair<F, S> {
private F first;
private S second;
}
@arturh からの回答のすべての利点(比較可能性を除く) がありhashCode
、、、、および静的な「コンストラクター」があります。equals
toString
Apache Commons Lang 3.0+にはいくつかのペアクラスがあります:http: //commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html
Pair with を実装する別の方法。
シンプルなファクトリなので、型を提供する必要はありません。例: 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 + ')';
}
}
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)
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);
}
}
何に使いたいかによります。これを行う典型的な理由は、マップを反復処理するためです。そのためには、これを行うだけです (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());
}
良いニュース 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
最大の問題は、おそらく、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)
Map.Entryインターフェイスは、c++ のペアにかなり近くなります。AbstractMap.SimpleEntryや AbstractMap.SimpleImmutableEntryなどの具体的な実装を見てください。最初の項目は getKey() で、2 番目は getValue() です。
私の意見では、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++ のユーザーはそれを理解できない場合があります。別の方法は、型引数に異なる境界を持つ型階層に多くのクラスを記述することですが、可能な境界とそれらの組み合わせが多すぎます...
JavaFX (Java 8 にバンドルされています) には Pair< A,B > クラスがあります
他の多くの人がすでに述べているように、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 のEqualsBuilder、HashCodeBuilder、およびToStringBuilderも参照してください。
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 を使用していて、それをコードで本当に示したい場合は、PositionX
とPositionY
を含むを定義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");
Collections.singletonMap(left, rigth);
簡単な方法 Object [] - 任意の次元のタプルとして使用できます
構文は似ていますが、Java と C++ には非常に異なるパラダイムがあります。Java のように C++ を書くのは悪い C++ であり、C++ のように Java を書くのは悪い Java です。
Eclipse のようなリフレクション ベースの IDE を使用すると、「ペア」クラスに必要な機能をすばやく簡単に記述できます。クラスを作成し、2 つのフィールドを定義し、さまざまな [Generate XX] メニュー オプションを使用して、数秒でクラスに入力します。Comparable インターフェイスが必要な場合は、「compareTo」をすばやく入力する必要があるかもしれません。
言語の個別の宣言/定義オプションを使用すると、C++ コード ジェネレーターはあまり良くないため、小さなユーティリティ クラスを手書きするのは、より時間がかかり退屈です。ペアはテンプレートであるため、使用しない関数に料金を支払う必要はなく、typedef 機能により、意味のある型名をコードに割り当てることができるため、「セマンティクスがない」という反対意見は実際には持ちこたえません。
たとえば、これは私のコードからのものです。
WeakHashMap<Pair<String, String>, String> map = ...
Haskell の Tuple と同じです。
便宜上、複数の程度のタプルを持ついくつかのライブラリを次に示します。
他のライブラリには、少なくともPair
タプルが含まれていると言及されています。
具体的には、(受け入れられた回答で提唱されているように)名目上の型付けではなく、多くの構造的な型付けを利用する関数型プログラミングのコンテキストでは、これらのライブラリとそのタプルは非常に便利です。
Java のようなプログラミング言語の場合、ほとんどのプログラマーがペアのようなデータ構造を表すために使用する代替データ構造は 2 つの配列であり、データは同じインデックスを介してアクセスされます。
例: http://www-igm.univ-mlv.fr/~lecroq/string/node8.html#SECTION0080
データを結合する必要があるため、これは理想的ではありませんが、非常に安価であることがわかります。また、ユースケースで座標を保存する必要がある場合は、独自のデータ構造を構築することをお勧めします。
図書館にこんなのあった
public class Pair<First,Second>{.. }
非常にシンプルで使いやすいバージョンが必要な場合は、https://github.com/lfac-pt/Java-Pairで入手できるようにしました。また、改善は大歓迎です!
com.sun.tools.javac.util.Pair は、ペアの単純な実装です。jdk1.7.0_51\lib\tools.jar にあります。
org.apache.commons.lang3.tuple.Pair 以外は、単なるインターフェースではありません。
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<T, U> can still return <code>true</code> for method <code>equals</code>
* called with a Pair<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<T, U></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 <v1, v2> of
* this pair and <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<T, U> can return <code>true</code> for equality testing with
* a Pair<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 での使用が試行されています。
これをパブリック ドメインでリリースするとは主張していないことに注意してください。これは私がアプリケーションで使用するために書いたばかりのコードなので、使用する場合は、直接コピーしてコメントや名前を少し変更することは控えてください。私のドリフトをキャッチしますか?
多くの人がマップのキーとして使用できるコードを投稿しています...ペアをハッシュキー(一般的なイディオム)として使用しようとしている場合は、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>
コードの多くの部分ではなく、このデータ構造を使い始めました。独自の中間マップクラスを指定するオプションを使用して、密な用途と疎な用途の両方に対応する配列、ツリー、およびその他の実装があります。
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();
不変、ペアのみ !
VAVR タプルを試してください。
vavr にはタプル型の優れたセットがあるだけでなく、関数型プログラミングも強力にサポートされています。