1

I would like to have a global HashMap <String, String> available to my whole project.

The hashmap will remain the same throughout the whole project, so it only needs to be instatiated once. My idea was to have it in a Utils class and have a static public class like so:

public static String  getValue(String key){
    return map.get(key);
}

The problem is, I don't want to have to run code to fill the hashmap with the Strings everytime I call getValue. So, where do I instantiate the code?

If I could fill the hashmap similar to:

HashMap hm = {{Key, Value}, {Key, Value}......} 

It could then be global to the utils class and would possibly work.

Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
Allan Macmillan
  • 1,481
  • 3
  • 18
  • 30

3 Answers3

5

You can instantiate it in a static block in the same Utils class.

static {
   // init code
}

Also you may want to look at the Singleton design pattern as an alternative to keeping static things (class, fields) as suggested here.

I assume your whole app/project is loaded by a single ClassLoader so you don't need to worry about static block called multiple times or Singleton objects instantiated multiple times (you want it instantiated just once).

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

You should use Joshua Bloch's "single element enum type" method, from this post. If your map should be immutable, consider an ImmutableMap from the guava library.

Community
  • 1
  • 1
Paul Sanwald
  • 10,899
  • 6
  • 44
  • 59
0
package pairtest;

import java.util.HashMap;

public class Util {

    private static final HashMap<String, String> map = new HashMap<>();
    private static Util instance = new Util();

    private Util() {
    }

    public static Util getInstance() {
        return instance;
    }

    public static String getValue(String key) {
        return map.get(key);
    }

    public static void add(String[][] pairs) {
        for(String[] pair : pairs) {
            map.put(pair[0], pair[1]);
        }
    }

    public static void add(String[] keys, String[] values) {
        for (int i = 0; i < keys.length; ++i) {
            map.put(keys[i], values[i]);
        }
    }
}


package pairtest;

public class PairTest {

    public static void main(String[] args) {
        String[][] arg = {{"key", "value"}, {"key", "value"}, {"key", "value"}};
        Util.add(arg);
    }
}
Brandon
  • 22,723
  • 11
  • 93
  • 186