简体   繁体   中英

How to avoid repetitive call of method in java?

I have written a method which returns a Hash Map. I am calling this method from many places at different methods every time the function will return the hash map with the same value. Is it possible to use the value returned from first call of the function instead of calling them every time.

If the method that returns the HashMap creates a new HashMap instance in each call, you can improve performance by caching the HashMap this method returns in an instance or static variable (depending if this is an instance method or static method) and returning that variable if it's not null.

private HashMap map; // I used a raw HashMap since I don't know what key and value your
                     // actual HashMap requires
public HashMap getMap () // you should consider returning a Map instead of a HashMap
{
    if (map == null) {
        map = new HashMap ();
        ... init the map ...
    }
    return map;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM