![]() ![]() In the documentation you can find the characteristics of these maps. Map.of, Map.ofEntries and Map.copyOf create unmodifiable maps. Since Java 9 (so you are excused if you were using Java 8 until recently) there are some factory methods present in the Map class. ![]() We are then assigning the Map to a HashMap reference HashMap map = new HashMap(Ĭreate an unmodifiable Map using a factory method In the example below, we are using the of() method to create a Map of key-value pairs. You can use this method to create a Map of key-value pairs and then assign the Map to a HashMap reference. This allow you to initialize a Map inline. The of() method is a static method of the Map class in Java that returns a Map. We are then passing the List to the HashMap constructor to initialize the HashMap. In the example above, we are using the asList() method to create a List of key-value pairs. New AbstractMap.SimpleEntry("Banana", 2), You can use this method to create a List of key-value pairs and then pass the List to the HashMap constructor to initialize the HashMap. The asList() method is a static method of the Arrays class in Java that returns a List. The second HashMap, map2, is created using the constructor, and it contains the same key-value pairs as map1. The first HashMap, map1, is created using the put() method. In the example above, we are creating two HashMaps. The HashMap constructor takes another Map as a parameter and creates a new HashMap that contains the same key-value pairs as the original Map. Initialization using the ConstructorĪnother way to initialize a HashMap is to use the HashMap constructor. We are then using the put() method to add three key-value pairs to the map. In the example above, we are creating a HashMap with String as the key type and Integer as the value type. You can add multiple key-value pairs to the HashMap by calling the put() method multiple times. ![]() The put() method allows you to add key-value pairs to the HashMap. One of the simplest ways to initialize a HashMap is to use the put() method. Initialization Initialization using the put() Method ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |