1

从地图中获取第一个值和第二个值的最佳方法是什么。我正在尝试阅读tableLists地图并first and second value从地图中获取。

下面是我ReadTableConnectionInfo的类代码。

private final LinkedHashMap<String, ReadTableConnectionInfo> tableLists;

ReadTableConnectionInfo table = tablePicker();


private ReadTableConnectionInfo tablePicker() {

    Random r = new SecureRandom();
    ReadTableConnectionInfo table;

    if (r.nextFloat() < Read.percentageTable / 100) {
        table = get first value from tableLists map
    } else {
        table = get second value from tableLists map
    }

    return table;
}
4

2 回答 2

1

假设您确定您的 LinkedHashMap 至少包含两个值,您可以这样做:

Iterator<Map.Entry<String, ReadTableConnectionInfo >> it = tableLists.entrySet().iterator();
if (r.nextFloat() < Read.percentageTable / 100) {
  table = it.next().getValue();
} else { //since you have an else, you have to re-ignore the first value just below
  it.next(); // ignoring the first value
  table = it.next().getValue(); //repeated here in order to get the second value
}
于 2013-02-24T03:55:10.010 回答
1

LinkedHashMap 值的迭代按插入顺序排序。所以 values() 是你需要的:

Iterator it = values().iterator();
Object first = it.next().getValue();
Object second = it.next().getValue();
于 2013-02-24T04:03:49.100 回答