This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details
Question: How do I initialize a HashMap directly (literally)?
Is there a way to initialize a Java HashMap like this?
Map<String,String> test =
new HashMap<String, String>{"test":"test","test":"test"};
Copy the code
What is correct grammar? I haven’t found any information about that yet. Is that possible? I’m looking for the shortest/fastest way to put some “final/static” values in the map that never change and are known in advance when the map is created.
Answer:
All versions
If you happen to only need one entry: there is collections.singletonMap (“key”, “value”). For Java version 9 or later:
Yes, it’s possible now. In Java 9, some factory methods were added to simplify map creation:
// this works for up to 10 elements:
Map<String, String> test1 = Map.of(
"a", "b",
"c", "d"
);
// this works for any number of elements:
import static java.util.Map.entry;
Map<String, String> test2 = Map.ofEntries(
entry("a", "b"),
entry("c", "d")
);
Copy the code
In the example above, test and test2 are the same, but they express the map differently. The map. of method can be defined for up to ten elements of a Map, and the map. ofEntries method does not have this limit.
Note that in this case, the generated map will be immutable. If you want the Map to be mutable, you can copy it again, for example using mutableMap = new HashMap<>(map.of (“a”, “b”));
(See also JEP 269 and Javadoc) For Java version 8:
No, you will have to add all elements manually. You can use initializers in anonymous subclasses to make the syntax shorter:
Map<String, String> myMap = new HashMap<String, String>() {{
put("a", "b");
put("c", "d");
}};
Copy the code
However, in some cases, anonymous subclasses may introduce unwanted behavior. This includes, for example:
It generates an additional class that increases memory consumption, disk space consumption, and startup time for non-static methods: it contains references to the object called by the creation method. This means that you cannot garbage collect objects of the external class while still referring to the map object you created, thus blocking additional memory
Using a function for initialization also enables you to generate mappings in the initializer, but avoids nasty side effects:
Map<String, String> myMap = createMap();
private static Map<String, String> createMap() {
Map<String,String> myMap = new HashMap<String,String>();
myMap.put("a", "b");
myMap.put("c", "d");
return myMap;
}
Copy the code
The article translated from yl2gl72eozkinivz3vc6swkesy – ac4c6men2g7xr2a – translate. Translate. Goog/questions / 6…
The authors suggest: be good with put, anonymous inner classes increase memory and are bad for garbage collection
Hashmap contains a lot of topics, such as jdk1.7’s head insertion loop problem, 1.8’s tail insertion problem, the initial capacity of hashmap, expansion, hash algorithm, thread safety (concurrenthashmap-cas +sync), and the calculation of size.
JDK1.8 size is obtained by CAS calculation of baseCount and counterCell, and finally by baseCount and counterCell traversal. The main idea is to improve throughput through arrays.
Thank you for reading this, if this article is well written and if you feel there is something to it
Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!
If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️