,java,intellij-idea,hashmap"/>

首页 > 解决方案 > 无法将值放入 HashMap

问题描述

任何想法为什么我无法put进入这个 HashMap?

public class UserImpl implements User{
   HashMap<String, Double> videoRecords = new HashMap<>();

   @Override
   public void updateVideoRecord(String currentVideo, double seconds) {
       videoRecords.put(currentVideo, seconds);
   }
}

IntelliJ 的调试器同时显示currentVideoseconds传递值,但 HashMapvideoRecords不更新。这是我用来检测 HashMap 不接受这些值的方法:

@Override
public void updateVideoRecord(String currentVideo, double seconds) {  
    System.out.println(this.videoRecords);
    this.videoRecords.put(currentVideo, seconds);
    System.out.println(this.videoRecords);
}

有趣的是,如果我在这个方法中初始化一个 HashMap,值就会成功地放入其中。

标签: javaintellij-ideahashmap

解决方案


如果您可以添加您的运行器代码或至少您的main()方法,那将会有所帮助。无论如何,我试图重现您的问题,但它似乎没有问题或任何问题。

这里我使用了UserImpl和你一样的类的实现,我只是添加了一个 get 方法,将地图返回给该main方法:

import java.util.*;
import java.util.HashMap;

public class UserImpl implements User {
   HashMap<String, Double> videoRecords = new HashMap<>();

   @Override
   public void updateVideoRecord(String currentVideo, double seconds) {
       videoRecords.put(currentVideo, seconds);
   }

   public HashMap<String, Double> getRecords() {
       return videoRecords;
   }
}

哪个从这个“模拟”接口实现,因为在您的实现中,您正在覆盖方法updateVideoRecord()

显然,在Main我创建类的一个对象时UserImpl,将一个新条目放入 HashMap 并在放置前后打印。

import java.util.*;

public class Main {
    public static void main(String[] args) {
        UserImpl userImpl = new UserImpl(); 
        HashMap<String, Double> records = userImpl.getRecords();
        System.out.println("The size of the map is " + records.size());
        System.out.println("Initial Mappings are: " + records); 
        userImpl.updateVideoRecord("theCurrentVideo", 360);
        System.out.println("The size of the map is " + records.size());
        System.out.println("Initial Mappings are: " + records); 
   }
}

最后,在这里您可以看到输出看起来完全符合您的要求,所以我看不到您的问题。因此,如果您能详细说明您的问题,也许我可以提供更好的帮助。如果没有,那么我希望这可以帮助您解决问题。

kareem@Kareems-MBP:Desktop$ javac Main.java
kareem@Kareems-MBP:Desktop$ java Main
The size of the map is 0
Initial Mappings are: {}
The size of the map is 1
Initial Mappings are: {theCurrentVideo=360.0}

推荐阅读