gpt4 book ai didi

java - 单键多个账户映射

转载 作者:行者123 更新时间:2023-12-02 05:44:58 26 4
gpt4 key购买 nike

我的 map 被声明为私有(private) map accountByReport;在将相应的部门帐户添加到 key 之前,我使用下面的循环来检查 reportID 是否在 map 中。我的循环是否正确?此实例中的类型声明应该是什么以及如何捕获异常?

 for(Entity entity : entities) {
if(accountsByReport.containsKey(entity.getReportID())) {
((List<String>)accountsByReport.get(entity.getReportID())).add(entity.getDepAccount());
} else {
accountsByReport.put(entity.getReportID(), new ArrayList<String>().add(entity.getDepAccount()));
}
}

最佳答案

您似乎正在向 else 中的 map 添加一个 boolean 值(返回 ok .add() )。我会用这种方式:

  for(Entity entity : entities) {
if(accountsByReport.containsKey(entity.getReportID())) {
((List<String>)accountsByReport.get(entity.getReportID())).add(entity.getDepAccount());
} else {
List<String> list = new ArrayList<String>();
list.add(entity.getDepAccount());
accountsByReport.put(entity.getReportID(), list);
}
}

您没有粘贴 map 定义,但您应该使用类型化参数 - 即 Map<String, List<String>> accountsByReport = new HashMap<String, List<String>>();所以你不需要在 .get 之后进行转换

事实上你粘贴了它。使用:private Map<String, List> accountByReport;

引用http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

关于java - 单键多个账户映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24161127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com