First method: Static block initialization
[Java]View PlainCopy
- Public class demo{
- private Static final map<string, string> MyMap;
- Static
- {
- MyMap = new hashmap<string, string> ();
- Mymap.put ("A", "B");
- Mymap.put ("C", "D");
- }
- }
Second method: Double-brace initialization (anonymous inner class)
[Java]View PlainCopy
- Hashmap<string, String > H = new hashmap<string, string> () {{
- Put ("a","B");
- }};
Caution, non-static inner class/Anonymous inner class contains a reference to a perimeter instance, and if you have a longer life cycle than the external class, there is a third method of memory leak: Guava
[Java]View PlainCopy
- Map<string, integer> left = Immutablemap.of ("A", 1, "B", 2, "C", 3);
- Or
- map<string, string> test = immutablemap.<string, String>builder ()
- . put ("K1", "v1")
- . put ("K2", "v2")
- ...
- . build ();
Java constructs map and initializes map