How do I insert values into a Map?

前端 未结 4 432
日久生厌
日久生厌 2020-12-11 14:46

I am trying to create a map of strings to strings. Below is what I\'ve tried but neither method works. What\'s wrong with it?

public class Data
{
    private         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 15:28

    The two errors you have in your code are very different.

    The first problem is that you're initializing and populating your Map in the body of the class without a statement. You can either have a static Map and a static {//TODO manipulate Map} statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.

    The second problem is that you cannot treat a Map syntactically like an array, so the statement data["John"] = "Taxi Driver"; should be replaced by data.put("John", "Taxi Driver"). If you already have a "John" key in your HashMap, its value will be replaced with "Taxi Driver".

提交回复
热议问题