【问题标题】:Array of map? integer string value pair mapping地图数组?整数字符串值对映射
【发布时间】:2013-02-11 17:25:34
【问题描述】:

我需要创建一个IntegerString配对,比如

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

稍后我想对其进行迭代并获取特定 Integer 值的 String, 说喜欢 如果是 int val == 2,则返回字符串。

我该怎么做?

【问题讨论】:

标签: java collections


【解决方案1】:

您可以使用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 的定义,给定整数不能有两个不同的字符串。如果您想允许这样做,您应该改用Map&lt;Integer, List&lt;String&gt;&gt;

请注意,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&lt;Pair&lt;Integer,String&gt;&gt;

【讨论】:

    【解决方案2】:

    Map&lt;Integer,String&gt; map = ...

    然后当你想遍历键时,使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 2021-11-15
      • 2014-10-31
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多