序文
以前の再開発プロセスで、2 つのクラスが存在することが判明しましたがPair
、2 つのペア クラス間にはまだいくつかの違いと接続があることがわかりました。研究内容はここに記録されます。PS: 将来的には、
トリプルTuplate
とマルチグループを探索することができます。
ペアクラス分析
javafx.util.Pair
JavaネイティブのPairクラス
デモの基本的な使い方。
package com.yanxml.util.pair.demo;
import javafx.util.Pair;
/**
* Pair 相关使用. Demo1
* @author seanYanxml
* @date 2022-02-28 00:00:00
*/
public class PairInstanceDemo1 {
public static void main(String[] args) {
// 创建
Pair createPair = new Pair<String, String>("abc","bcd");
// 获取左边值
System.out.println("key:" + createPair.getKey());
// 获取右边值
System.out.println("Value:" + createPair.getValue());
// Pair 创建完成后. 无法修改.
}
}
期待される出力:
key:abc
Value:bcd
詳しい説明
构造函数
getKey
構造を見ると、このクラスにはこれらの基本的なメンバーとメソッドがあり、その中で最も重要なのはとgetValue
これら 3 つのメソッドであることがわかります。
package javafx.util;
import java.io.Serializable;
import javafx.beans.NamedArg;
/**
* <p>A convenience class to represent name-value pairs.</p>
* @since JavaFX 2.0
*/
public class Pair<K,V> implements Serializable{
/**
* Key of this <code>Pair</code>.
*/
private K key;
/**
* Gets the key for this pair.
* @return key for this pair
*/
public K getKey() { return key; }
/**
* Value of this this <code>Pair</code>.
*/
private V value;
/**
* Gets the value for this pair.
* @return value for this pair
*/
public V getValue() { return value; }
/**
* Creates a new pair
* @param key The key for this pair
* @param value The value to use for this pair
*/
public Pair(@NamedArg("key") K key, @NamedArg("value") V value) {
this.key = key;
this.value = value;
}
/**
* <p><code>String</code> representation of this
* <code>Pair</code>.</p>
*
* <p>The default name/value delimiter '=' is always used.</p>
*
* @return <code>String</code> representation of this <code>Pair</code>
*/
@Override
public String toString() {
return key + "=" + value;
}
/**
* <p>Generate a hash code for this <code>Pair</code>.</p>
*
* <p>The hash code is calculated using both the name and
* the value of the <code>Pair</code>.</p>
*
* @return hash code for this <code>Pair</code>
*/
@Override
public int hashCode() {
// name's hashCode is multiplied by an arbitrary prime number (13)
// in order to make sure there is a difference in the hashCode between
// these two parameters:
// name: a value: aa
// name: aa value: a
return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
}
/**
* <p>Test this <code>Pair</code> for equality with another
* <code>Object</code>.</p>
*
* <p>If the <code>Object</code> to be tested is not a
* <code>Pair</code> or is <code>null</code>, then this method
* returns <code>false</code>.</p>
*
* <p>Two <code>Pair</code>s are considered equal if and only if
* both the names and values are equal.</p>
*
* @param o the <code>Object</code> to test for
* equality with this <code>Pair</code>
* @return <code>true</code> if the given <code>Object</code> is
* equal to this <code>Pair</code> else <code>false</code>
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof Pair) {
Pair pair = (Pair) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
return true;
}
return false;
}
}
上記のコードから、ペアの左側と右側は 2 つのオブジェクトによって完成されていることがわかります。これは、通常使用するクラスによって定義されているメンバー変数と何ら変わりません。
ただし、Pair には変更メソッドがないことに注意してください。つまり、Pair が宣言されると、その中の変数は不変になります。
org.apache.commons.lang3.tuple.Pair
lang3 パッケージのペアクラス
Java要素のPairパッケージを見た後、lang3
Pairクラスがどのように定義されているかを見てみましょう。
- デモメソッド
package com.yanxml.util.pair.demo;
import org.apache.commons.lang3.tuple.Pair;
/**
* Pair 相关使用. Demo2
* @author seanYanxml
* @date 2022-02-28 00:00:00
*/
public class PairInstanceDemo2 {
public static void main(String[] args) {
Pair<String, String> demoPair = Pair.of("hello", "world");
// 获取
System.out.println("Key:" + demoPair.getKey());
System.out.println("Value:" + demoPair.getValue());
// 左右获取
System.out.println("Left:" + demoPair.getLeft());
System.out.println("Right:" + demoPair.getRight());
// 更新值 会抛出异常.
demoPair.setValue("123");
}
}
- 試験結果
Key:hello
Value:world
Left:hello
Right:world
Exception in thread "main" java.lang.UnsupportedOperationException
at org.apache.commons.lang3.tuple.ImmutablePair.setValue(ImmutablePair.java:100)
at com.yanxml.util.pair.demo.PairInstanceDemo2.main(PairInstanceDemo2.java:24)
テスト結果から、このペア クラスは宣言方法以外はネイティブのペアと何も変わらないことがわかり、
さらにペア内のオブジェクトを変更しようとすると例外がスローされます。
org.apache.commons.lang3.tuple.Pair
ソースコード分析
- org.apache.commons.lang3.tuple.Pair
- org.apache.commons.lang3.tuple.ImmutablePair
ソースコードを個別に見てみると、非常に興味深い箇所がわかります。
package org.apache.commons.lang3.tuple;
import java.io.Serializable;
import java.util.Map.Entry;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;
public abstract class Pair<L, R> implements Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
private static final long serialVersionUID = 4954918890077093841L;
public Pair() {
}
public static <L, R> Pair<L, R> of(L left, R right) {
return new ImmutablePair(left, right);
}
public abstract L getLeft();
public abstract R getRight();
public final L getKey() {
return this.getLeft();
}
public R getValue() {
return this.getRight();
}
public int compareTo(Pair<L, R> other) {
return (new CompareToBuilder()).append(this.getLeft(), other.getLeft()).append(this.getRight(), other.getRight()).toComparison();
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof Entry)) {
return false;
} else {
Entry<?, ?> other = (Entry)obj;
return ObjectUtils.equals(this.getKey(), other.getKey()) && ObjectUtils.equals(this.getValue(), other.getValue());
}
}
public int hashCode() {
return (this.getKey() == null ? 0 : this.getKey().hashCode()) ^ (this.getValue() == null ? 0 : this.getValue().hashCode());
}
public String toString() {
return "" + '(' + this.getLeft() + ',' + this.getRight() + ')';
}
public String toString(String format) {
return String.format(format, this.getLeft(), this.getRight());
}
}
package org.apache.commons.lang3.tuple;
public final class ImmutablePair<L, R> extends Pair<L, R> {
private static final long serialVersionUID = 4954918890077093841L;
public final L left;
public final R right;
public static <L, R> ImmutablePair<L, R> of(L left, R right) {
return new ImmutablePair(left, right);
}
public ImmutablePair(L left, R right) {
this.left = left;
this.right = right;
}
public L getLeft() {
return this.left;
}
public R getRight() {
return this.right;
}
public R setValue(R value) {
throw new UnsupportedOperationException();
}
}
ペア メソッド内には、2 つの主要なコンストラクターがあることがわかります。
# Pair 类
public Pair() {
}
public static <L, R> Pair<L, R> of(L left, R right) {
return new ImmutablePair(left, right);
}
# ImmutablePair 类
public final class ImmutablePair<L, R> extends Pair<L, R> {
private static final long serialVersionUID = 4954918890077093841L;
public final L left;
public final R right;
public static <L, R> ImmutablePair<L, R> of(L left, R right) {
return new ImmutablePair(left, right);
}
public ImmutablePair(L left, R right) {
this.left = left;
this.right = right;
}
}
実際、Pair.of()
実際のインスタンス化によく使用されるのはImmutablePair
不変のペア クラスであり、これは、set メソッドの実行時に例外がスローされる理由も説明しています。
# ImmutablePair 类 中
public R setValue(R value) {
throw new UnsupportedOperationException();
}
もう 1 つの興味深い点は、このペア クラスは set メソッドを提供しますが、このメソッドを実行すると例外がスローされることです。これは、前のテスト コードでも関連する例外です。
要約する
この章では主に 2 つのペア クラスの関連する使用法を紹介し、関連するソース コードを表示します。次のような違いがあります。
共通点
- 定義にジェネリックを使用します。
class Pair<K,V>
これにより、ジェネリックの利点が反映され、拡張が容易になります。 - 定義されたペア内には
get
メソッドのみが存在し、set
メソッドは存在しません。
違い
- オブジェクトの宣言方法が異なりますが、本質的な違いはありません。
- JavaのネイティブのPairクラスは
new Pair<K,V> (key,value)
この方法で宣言する必要があります。 - 宣言にはLang3のPairクラスがよく使われます
Pair.of(key,value)
。
- JavaのネイティブのPairクラスは
getKey/getValue
Lang3 のペア クラスは、メソッドに加えて、getLeft/getRight
このメソッドのペアを追加で提供します。
参照
[ソースコード] [javafx.util.Pair]
[ソースコード] [org.apache.commons.lang3.tuple.Pair]