您可以使用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<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>>。