Sambhav Sharma
Sambhav Sharma

Reputation: 5860

Initializing List with definition

I was implementing a Java application when I came across this scenario and couldn't find which way is better to do it and why. following is the scenario.

I have a static list that will load data on application startup.

In my ApplicationStartup class I have

public static List<Map<String,Object>> stockSymbolsListMap;

Now when I load this List using a function in my Utility class I have the following code:

//Check if the list has been initialized or not
if(ApplicationStartup.stockSymbolsListMap == null){

    ApplicationStartup.stockSymbolsListMap = new ArrayList<Map<String,Object>>();

    } else if(!(ApplicationStartup.stockSymbolsListMap.isEmpty())){

        // Clear the list to avoid redundancy
        ApplicationStartup.stockSymbolsListMap.clear();

    }

    // Adding all stock symbols to the list
    while(allStockSymbols.hasNext()){
        ApplicationStartup.stockSymbolsListMap.add(allStockSymbols.next().toMap());
    }

Isn't it better that I initialize this list in my ApplicationStartup class itself?

public static List<Map<String,Object>> stockSymbolsListMap = new ArrayList<Map<String,Object>>();

Upvotes: 0

Views: 76

Answers (2)

Bassem Reda Zohdy
Bassem Reda Zohdy

Reputation: 12942

what I can see that the list is static so it will be called by class and to initialize it you are going to use static code, so the initialization will not be repeated, so why you need to use this way to initialize it, for me I prefer to use singleton bean instead of using static elements.

Upvotes: 1

arshajii
arshajii

Reputation: 129537

It depends. Your first approach is akin to a lazy initialization, which could be beneficial. If you don't need stockSymbolsListMap right away, then why initialize it? On the other hand, if the initialization is very cheap, then for simplicity you might consider initializing the list immediately. Overall, do whichever makes more sense in the context of your program, and whichever will be easiest to maintain in the future.

Upvotes: 1

Related Questions