A simple way to declare static map constants in Java

Source: Internet
Author: User

I now need to put a hashmap in a class, put some data inside, each time to fetch data from the database to find the HashMap, see if there is already exist, if there is a direct extraction, if not exist to extract data from the database and then put into HashMap, Should you set the HashMap as a static variable for the class?

If you set public static HashMap Hmdata, you will not be able to add data to the Hmspace, should I new an object?

Common declarative methods (using static blocks of code):

Java code
    1. Public final static Map map = new HashMap ();
    2. static {
    3. Map.put ("Key1", "value1");
    4. Map.put ("Key2", "value2");
    5. }



A simple way to:

Java code
    1. Public final static Map map = new HashMap () {{
    2. Put ("Key1", "value1");
    3. Put ("Key2", "value2");
    4. }};

This approach is equivalent to an anonymous implementation of the overloaded HashMap. An anonymous construction method was added to the original HashMap.


Another way to add a List/set variable is to declare it:

Java code
    1. Public final static List List = Arrays.aslist ("Elment1", "Element2");

A simple way to declare static map constants in Java

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.