猿问

无法将值放入 HashMap<String,双精度>

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


public class UserImpl implements User{

   HashMap<String, Double> videoRecords = new HashMap<>();


   @Override

   public void updateVideoRecord(String currentVideo, double seconds) {

       videoRecords.put(currentVideo, seconds);

   }

}

IntelliJ的调试器显示两者并传递值,但HashMap不会更新。以下是我用来检测HashMap不接受这些值的内容:currentVideosecondsvideoRecords


@Override

public void updateVideoRecord(String currentVideo, double seconds) {  

    System.out.println(this.videoRecords);

    this.videoRecords.put(currentVideo, seconds);

    System.out.println(this.videoRecords);

}

有趣的是,如果我在此方法中初始化HashMap,则值将成功放入其中。


蝴蝶刀刀
浏览 76回答 1
1回答

繁星点点滴滴

如果您可以添加您的运行器代码或至少您的方法,那将有所帮助。无论如何,我试图重现您的问题,但它似乎没有任何问题或任何东西。main()在这里,我像你一样使用了相同的类实现,我只是添加了一个get方法,将映射返回到该方法:UserImplmainimport java.util.*;import java.util.HashMap;public class UserImpl implements User {&nbsp; &nbsp;HashMap<String, Double> videoRecords = new HashMap<>();&nbsp; &nbsp;@Override&nbsp; &nbsp;public void updateVideoRecord(String currentVideo, double seconds) {&nbsp; &nbsp; &nbsp; &nbsp;videoRecords.put(currentVideo, seconds);&nbsp; &nbsp;}&nbsp; &nbsp;public HashMap<String, Double> getRecords() {&nbsp; &nbsp; &nbsp; &nbsp;return videoRecords;&nbsp; &nbsp;}}它从这个“Mock”接口实现,因为在您的实现中,您正在重写方法。updateVideoRecord()显然,在我创建类的对象中,将一个新条目放入HashMap并在放置之前和之后打印。MainUserImplimport java.util.*;public class Main {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; UserImpl userImpl = new UserImpl();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; HashMap<String, Double> records = userImpl.getRecords();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("The size of the map is " + records.size());&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Initial Mappings are: " + records);&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; userImpl.updateVideoRecord("theCurrentVideo", 360);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("The size of the map is " + records.size());&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Initial Mappings are: " + records);&nbsp;&nbsp; &nbsp;}}最后,在这里您可以看到输出看起来完全符合预期,因此我没有看到您的问题。因此,如果你能更详细地阐述你的问题,也许我可以提供更好的帮助。如果没有,那么我希望这有助于您解决问题。kareem@Kareems-MBP:Desktop$ javac Main.javakareem@Kareems-MBP:Desktop$ java MainThe size of the map is 0Initial Mappings are: {}The size of the map is 1Initial Mappings are: {theCurrentVideo=360.0}
随时随地看视频慕课网APP

相关分类

Java
我要回答