Integer
次のように、String
ペアリングを作成する必要があります
(1,one)
(2,two)
(3,three)
後で私はそれを繰り返してString
、特定のInteger
値を取得したいと思います.if intのようval == 2
に、文字列を返します.
これどうやってするの?
Integer
次のように、String
ペアリングを作成する必要があります
(1,one)
(2,two)
(3,three)
後で私はそれを繰り返してString
、特定のInteger
値を取得したいと思います.if intのようval == 2
に、文字列を返します.
これどうやってするの?
Map<Integer,String> map = ...
次に、キーを反復処理する場合は、使用します
map.keySet()
キーとして使用される整数のリストを取得する
を使用して、このペアリングの関連付けをモデル化できますMap
。
Map m = new HashMap<Integer, String>();
m.put(1, "one");
m.put(2, "two");
m.put(3, "three");
// Iterate the keys in the map
for (Entry<Integer, String> entry : m.entrySet()){
if (entry.getKey().equals(Integer.valueOf(2)){
System.out.println(entry.getValue());
}
}
Map
の定義により、特定の整数に対して 2 つの異なる文字列を持つことはできないことを考慮してください。これを許可したい場合は、Map<Integer, List<String>>
代わりに a を使用する必要があります。
Java はPair
クラスを提供していませんが、自分で実装できることに注意してください。
public class Pair<X,Y> {
X value1;
Y value2;
public X getValue1() { return value1; }
public Y getValue2() { return value2; }
public void setValue1(X x) { value1 = x; }
public void setValue2(Y y) { value2 = y; }
// implement equals(), hashCode() as needeed
}
そして、を使用しList<Pair<Integer,String>>
ます。