-4

Integer次のように、Stringペアリングを作成する必要があります

(1,one)
(2,two)
(3,three)

後で私はそれを繰り返してString、特定のInteger値を取得したいと思います.if intのようval == 2に、文字列を返します.

これどうやってするの?

4

2 に答える 2

0

Map<Integer,String> map = ...

次に、キーを反復処理する場合は、使用します

map.keySet()キーとして使用される整数のリストを取得する

于 2013-02-11T17:27:53.117 に答える
0

を使用して、このペアリングの関連付けをモデル化できます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>>ます。

于 2013-02-11T17:28:11.443 に答える