我有一张类似这样的 map -
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}}
我正在尝试迭代上面的 map -
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
0 和 1 取决于 tableLists
尺寸。
更新的代码:-
进行这样的更改后-
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,但这一次它在建立连接并返回后立即抛出。我在这里做错了什么?
最佳答案
Map
接口(interface)有一个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++;
}
关于java - 使用索引从 Map 中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14844512/