java - 使用索引从 Map 中检索值

标签 java hashmap concurrenthashmap

我有一张类似这样的 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 Exceptionget 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/

相关文章:

java - 如何在 Java 中创建自己的 HashMap?

java - 静态ConcurrentHashmap是否需要外部同步

java - 如何防止 CompletableFuture#whenComplete 在上下文线程中执行

java - 带有 @EmbeddedId 的 StackOverflowError

java - Android 广播接收器仅处于待机状态或应用程序不活动状态

java - FX - 在网格中对齐复选框的建议

rust - 交换 HashMap 的两个条目

java - Integer 不是一个引用吗?为什么 inc 不更新 hashmap 值?

java - Collectors.toConcurrentMap 和通过 Collectors.toMap 供应商选项将 Map 转换为 ConcurrentHashMap 之间有什么区别?

java - 如何从数组中取出空空格?