JavaでKeyValuePairクラスを探しています。
java.utilはインターフェースを多用するため、具体的な実装は提供されず、Map.Entryインターフェースのみが提供されます。
インポートできる標準的な実装はありますか?これは、私が100倍の回数実装するのが嫌いな「配管工プログラミング」クラスの1つです。
クラスAbstractMap.SimpleEntryは汎用であり、便利な場合があります。
AndroidプログラマーはBasicNameValuePairを使用できます
アップデート:
BasicNameValuePairは非推奨になりました(API 22)。代わりにペアを使用してください。
使用例:
Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"
Commons LangのPairクラスは、次の場合に役立ちます。
Pair<String, String> keyValue = new ImmutablePair("key", "value");
もちろん、commons-langを含める必要があります。
インスタンス化できる任意の2つのタイプの最も単純なKey-Valueペアリングには、 javafx.util.Pairの使用で十分です。
Pair<Integer, String> myPair = new Pair<>(7, "Seven");
Integer key = myPair.getKey();
String value = myPair.getValue();
import java.util.Map;
public class KeyValue<K, V> implements Map.Entry<K, V>
{
private K key;
private V value;
public KeyValue(K key, V value)
{
this.key = key;
this.value = value;
}
public K getKey()
{
return this.key;
}
public V getValue()
{
return this.value;
}
public K setKey(K key)
{
return this.key = key;
}
public V setValue(V value)
{
return this.value = value;
}
}
使うのが好き
例:
Properties props = new Properties();
props.setProperty("displayName", "Jim Wilson"); // (key, value)
String name = props.getProperty("displayName"); // => Jim Wilson
String acctNum = props.getProperty("accountNumber"); // => null
String nextPosition = props.getProperty("position", "1"); // => 1
あなたがハッシュテーブルに精通しているなら、あなたはすでにこれにかなり精通しているでしょう
カスタムKeyValuePairクラスを簡単に作成できます
public class Key<K, V>{
K key;
V value;
public Key() {
}
public Key(K key, V value) {
this.key = key;
this.value = value;
}
public void setValue(V value) {
this.value = value;
}
public V getValue() {
return value;
}
public void setKey(K key) {
this.key = key;
}
public K getKey() {
return key;
}
}
私のお気に入りは
HashMap<Type1, Type2>
Type1のキーのデータ型と、Type2の値のデータ型を指定するだけです。これは、Javaで見た中で最も一般的なKey-Valueオブジェクトです。
https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Mavenで利用可能なGlobalMentorのコアライブラリNameValuePair
にクラスを公開しました。これは長い歴史を持つ進行中のプロジェクトですので、変更や改善のリクエストを送信してください。
Hashtable<String, Object>
java.util.Properties
それは実際にはの拡張であるよりも優れていHashtable<Object, Object>
ます。