Java constructs map and initializes map

Source: Internet
Author: User

First method: Static block initialization

[Java]View PlainCopy
  1. Public class demo{
  2. private Static final map<string, string> MyMap;
  3. Static
  4. {
  5. MyMap = new hashmap<string, string> ();
  6. Mymap.put ("A", "B");
  7. Mymap.put ("C", "D");
  8. }
  9. }

Second method: Double-brace initialization (anonymous inner class)

[Java]View PlainCopy
    1. Hashmap<string, String > H = new hashmap<string, string> () {{
    2. Put ("a","B");
    3. }};


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
    1. Map<string, integer> left = Immutablemap.of ("A", 1, "B", 2, "C", 3);
    2. Or
    3. map<string, string> test = immutablemap.<string, String>builder ()
    4. . put ("K1", "v1")
    5. . put ("K2", "v2")
    6. ...
    7. . build ();

Java constructs map and initializes map

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.