java - 无法将值放入 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 的调试器同时显示currentVideo
并seconds
传递值,但 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,值就会成功地放入其中。
解决方案
如果您可以添加您的运行器代码或至少您的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}
推荐阅读
- javascript - 如果对象中没有键,我无法将空值传递给 html 属性。请提出这个建议,我怎样才能更好地做到这一点
- android - 有没有办法在Android中以编程方式更改子字符串的颜色?
- arrays - 找到总和最大的一对非重叠子数组
- java - 如何以 for(a!:b){loop} 形式循环某些内容
- javascript - 每次触发事件时,如何逐个循环添加一个 classList 值?
- c# - 命名具有可变内容的对象以在 json 文件中序列化
- css - 对齐网格区域中的多个项目
- c# - 动态 linq 库中有没有办法选择...列开始的地方
- garbage-collection - G1GC 垃圾收集器
- c# - 如果 cookie 在 asp.net 中不存在,如何创建它?