![]() Rather than the Java: m1.put(“BY”, “Belarus”)Īlso, the map is by default mutable, which is arguably good or bad, depending on the needs. Note that we use the expression: m1 = “Belarus” The syntax is very straightforward, somewhat reminiscent of Python’s dictionaries, and no need to remember the various contortions necessary if you have an initial list longer than ten pairs. Once again, you see how Groovy simplifies the situation. When you run the Groovy version, you see: m1 = Take a look at the Groovy version of the above: def m1 = [ Here, by using the immutable map created by Map.ofEntries() as an argument to the HashMap constructor, I create a mutable copy of it, which I can then alter-for example, with the put() method. ("m3 is an instance of " + m3.getClass()) However, supposing I want to create and initialize a map instance with some entries and later add to that map, I need to do something like this: var m3 = new HashMap(Map.ofEntries( Note above that rather than using Map.of() as in the first example, I used Map.ofEntries(). ("m2 is an instance of " + m2.getClass()) Īs long as I don’t need to subsequently change the contents of the map created and initialized with Map.ofEntries(), this is a decent solution. You’ll see the Java compiler looking for a version of Map.of() that accepts 11 pairs and fails.Ī quick look at the documentation for shows the reason for this second limitation, and shows a way out of that conundrum: var m2 = Map.ofEntries( ![]() Try adding tenth and eleventh pairs, say "AG", "Antigua and Barbuda", and "AR", "Argentina" to see what happens. Second, this way you can supply at most 20 arguments, representing ten key-value pairs. First, the map instance you create this way is immutable. ![]() It turns out that Map.of() used in this fashion bears two important restrictions. ("m1 is an instance of " + m1.getClass()) The most obvious candidate is the static method () which you can use as follows: var m1 = Map.of( Java offers a number of ways to instantiate and initialize maps, and since Java 9, several new approaches got added.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |