【问题标题】:Problem adding list from on Hashmap to another将 Hashmap 上的列表添加到另一个列表时出现问题
【发布时间】:2019-09-09 06:59:48
【问题描述】:

问题将一个列表从一个哈希映射的值添加到另一个哈希映射的值

基本上,我有 2 个哈希图(map1 和 map2),它们都有相同的键(0-500 的整数),但值不同。我想要做的是使用 map1 的值,它是一个字符串,作为键和 map2 的值,它是一个列表,作为值。将 map1 添加为 key 可以正常工作,没问题,但是当我尝试将 map2 的值添加为 map 的值时,它只是返回为 null。

这是一个家庭作业项目,我们有 2 个 .csv 文件,一个带有标签,另一个带有假图像文件名,并且必须能够通过图像标签或图像文件名进行搜索。

Map<String, List<String>> map = new HashMap<String, List<String>>();

    @SuppressWarnings({ "resource", "null", "unlikely-arg-type" })
    public ImageLabelReader(String labelMappingFile, String imageMappingFile) throws IOException {
        Map<Integer, String> map1 = new HashMap<Integer, String>();
        Map<Integer, List<String>> map2 = new HashMap<Integer, List<String>>();
        BufferedReader labelIn = new BufferedReader(new FileReader(labelMappingFile));
        BufferedReader imageIn = new BufferedReader(new FileReader(imageMappingFile));
        String row;
        String[] rowArray;
        while ((row = labelIn.readLine()) != null) {
            rowArray = row.split(" ", 2);
            map1.put(Integer.parseInt(rowArray[0]), rowArray[1]);
            }
        labelIn.close();
        while ((row = imageIn.readLine()) != null) {
            rowArray = row.split(" ", 2);
            if(map2.containsKey(Integer.parseInt(rowArray[1]))) {
                List<String> tempList = map2.get(Integer.parseInt(rowArray[1]));
                tempList.add(rowArray[0]);
            } else {
                List<String> l = new ArrayList<String>();
                l.add(rowArray[0]);
                map2.put(Integer.parseInt(rowArray[1]), l);
            }
        }
        imageIn.close();
        List<String> t = new ArrayList<String>();
        for(int i = 0; i < map1.size(); i++) {
            t.clear();
            for(String s : map2.get(i)) {
                t.add(s);
                System.out.println(t);
            }

            map.put(map1.get(i), map2.get(i));

        }

        System.out.println(map.containsKey("burrito"));
        System.out.print(map2.get("burrito"));
    }

当输出应为“True [包含字符串的列表]”时,输出为“True null”

【问题讨论】:

  • 你打电话给map.containsKey,但是map2.get。那是错字吗?你的意思是访问同一个地图吗?应该是map.get("burrito")
  • 你不应该使用map.put(map1.get(i), t); 而不是map.put(map1.get(i), map2.get(i));
  • 这是一个错误——我已经完全掩盖了这一点......现在我看到它有效。感谢您的帮助!
  • map2.get("burrito") map2 的键是整数。而“burrito”是一个字符串

标签: java list arraylist hashmap


【解决方案1】:

尝试替换 -

map.put(map1.get(i), map2.get(i));

map.put(map1.get(i), t);

还有-

System.out.print(map2.get("burrito"));

System.out.print(map.get("burrito"));

另外,当您说密钥是 int 类型时,您正尝试使用 String 获取地图的值,请检查。

【讨论】:

    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2021-08-18
    • 2015-04-29
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    相关资源
    最近更新 更多