How do I initialize HashMap myself?

Asked 2 years ago, Updated 2 years ago, 167 views

Map<String,String> test = new HashMap<String, String>{"test":"test","test":"test"}; Is there a way to initialize HashMap like the code above? Is the code above grammatically correct?

java collections map initialization

2022-09-22 22:31

1 Answers

You can't use the code above. You have to add them to the elements one by one.

public class Demo
{
    private static final Map<String, String> myMap;
    static
    {
        myMap = new HashMap<String, String>();
        myMap.put("a", "b");
        myMap.put("c", "d");
    }
}


2022-09-22 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.