地图阵列?整数字符串值对映射



我需要创建IntegerString配对,如

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

稍后,我想对其进行迭代,并获得特定CCD_ 4值的CCD_,说喜欢如果int val == 2,则返回String。

我该怎么做?

您可以使用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的定义,对于给定的Integer,不能有两个不同的String。如果您想允许这样做,您应该使用Map<Integer, List<String>>

请注意,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>>

Map<Integer,String> map = ...

然后,当你想迭代密钥时,使用

map.keySet()获取用作密钥的整数列表

相关内容

最新更新