Lokesh Sanapalli
Lokesh Sanapalli

Reputation: 1034

How to declare HashMap in global and add values into it only for the first time?

I am using an HashMap in every method and adding values to it, like this...

LinkedHashMap<String,String> ProductList = new LinkedHashMap<String,String>();
    ProductList.put("107070706", "Hello");
    ProductList.put("107070707", "Bye");
    ProductList.put("107070708", "World");
    ProductList.put("107070709", "SeeYou");

I want to declare it inside the class and has to assign values so that I can use this later in my own methods...

How can I do that?

Note: I got an idea to implement this adding elements part in a constructor, but It doesn't fit to my requirement.

Upvotes: 2

Views: 12552

Answers (1)

JonK
JonK

Reputation: 2108

Provided that the Map should be shared across every instance of your class, then you need to make it static. You then use a static initialiser block to instantiate and populate it:

public class SomeClass {

    // Note that I've typed to Map instead of LinkedHashMap, and that it is now static
    static final Map<String, String> PRODUCT_LIST;

    static {
        PRODUCT_LIST = new LinkedHashMap<>(); // Diamond operator requires Java 1.7+
        PRODUCT_LIST.put("107070706", "Hello");
        PRODUCT_LIST.put("107070707", "Bye");
        PRODUCT_LIST.put("107070708", "World");
        PRODUCT_LIST.put("107070709", "SeeYou");
    }

    // Rest of your code here
}

Static initalisers only execute once, when the class is first loaded by a ClassLoader. This means you're not re-doing a bunch of work each time you create an instance of your class.

Typically static final variables are named in ALL_UPPER_CASE, so really it should be called PRODUCT_LIST.

Upvotes: 3

Related Questions