繁体   English   中英

无法将值放入HashMap <String, double>

[英]Unable to put values into HashMap<String, double>

有什么想法为什么我无法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都在传递值,但是HashMap videoRecords不会更新。 这是我用来检测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}

谢谢你的帖子。 我已经尝试调试了好几个小时,根据您的回答,没有理由认为该代码无法正常工作。 你是对的。

我正在尝试扩展别人的现有代码,这是导致我的代码无法正常工作的原因。 HashMap videoRecords正在被Serialized videoRecords文件,但是在此过程中, toString()方法正在擦除其旁边的所有记录。

我花了几个小时才弄清楚这一点...

@Kareem Jeiroudi:感谢您指出正确的方向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM