How do I insert values into a Map?

前端 未结 4 433
日久生厌
日久生厌 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

    There are two issues here.

    Firstly, you can't use the [] syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.

    data.put is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:

    public class Data {
         public static void main(String[] args) {
             Map data = new HashMap();
             data.put("John", "Taxi Driver");
             data.put("Mark", "Professional Killer");
         }
     }
    

    If you want to initialize a map as a static field of a class then you can use Map.of, since Java 9:

    public class Data {
        private static final Map DATA = Map.of("John", "Taxi Driver");
    }
    

    Before Java 9, you can use a static initializer block to accomplish the same thing:

    public class Data {
        private static final Map DATA = new HashMap<>();
    
        static {
            DATA.put("John", "Taxi Driver");
        }
    }
    

提交回复
热议问题