使用索引从Map中检索值

时间:2013-02-13 00:34:34

标签: java hashmap concurrenthashmap

我有一张这样的地图 -

ConcurrentHashMap<String, ConcurrentHashMap<String, String>> tableList

将有这样的数据 -

示例 -

{table1={DRIVER=oracle.jdbc.driver.OracleDriver, PASSWORD=stage_cs_user, URL=jdbc_url, SUFFIX=xt1, SQL=sql, USER=user}, table2={DRIVER=driver_name, PASSWORD=pass, URL=jdbc_url2, SUFFIX=xt2, SQL=sql2, USER=user}}

我正在尝试迭代上面的地图 -

class Task implements Runnable {

private Connection[] dbConnection = null;
private final ConcurrentHashMap<String, ConcurrentHashMap<String, String>> tableLists;

public Task(ConcurrentHashMap<String, ConcurrentHashMap<String, String>> tableNames) {
    this.tableLists = tableNames;
}

@Override
public void run() {

for (int i = 0; i < tableLists.size(); i++) {

dbConnection[i] = getDBConnection(tableLists.get(i).get("URL"), tableLists.get(i).get("USERNAME"), tableLists.get(i).get("PASSWORD"), tableLists.get(i).get("DRIVER"));
    }
  }
}

它在Null Pointer Exception中给了我get call。这里有什么我想念的吗?如果是,我该如何解决?我需要根据dbConnection大小将tableLists指定为0和1。

更新代码: -

进行这样的更改后 -

private Connection[] dbConnection = null;


        int j=0;
        for (Map<String, String> map : tableLists.values()) {

            dbConnection[j] = getDBConnection(map.get("URL"), map.get("USER"), map.get("PASSWORD"), map.get("DRIVER"));
            callableStatement[j] = dbConnection[j].prepareCall(map.get("SQL"));

            methods[j] = getRequiredMethods(map.get("SUFFIX"));
            j++;
        }

private Connection getDBConnection(String url, String username, String password, String driver) {

    Connection dbConnection = null;

    try {
        Class.forName(driver);
        dbConnection = DriverManager.getConnection(url, username, password);
    }

    return dbConnection;
}

它再次投掷NPE,但这次它在连接并返回后立即投掷。我在这做错了什么?

2 个答案:

答案 0 :(得分:1)

Map接口有Key,而不是索引。要获取所有条目,请尝试

int i=0;
dbConnection = new DbConnection[tableLists.size()];
for (Map<String, String> map : tableLists.values()) {
  dbConnection[i] = getDBConnection(
    map.get("URL"), 
    map.get("USER"), 
    map.get("PASSWORD"), 
    map.get("DRIVER"));
  i++;
}

答案 1 :(得分:0)

你不应该得到像

这样的值
tableLists.get(0);
tableLists.get(1);

由于Map不是基于索引的集合,因此它的密钥基础。您应该获得像

这样的值
tableLists.get("table1");
tableLists.get("table2");

因为你的密钥是“table1”和“table2”而不是0和1。

修改 的 因此,您可以修改您的来源,如下所示。

int i = 0;
for (String mapkey : tableLists.keySet()) {
    dbConnection[i] = getDBConnection(
            tableLists.get(mapkey).get("URL"), 
            tableLists.get(mapkey).get("USERNAME"),
            tableLists.get(mapkey).get("PASSWORD"),
            tableLists.get(mapkey).get("DRIVER"));
    i++;
}