How to initialize the public static read-only LinkedMap (bi-directional map)

I would like to create

public static final LinkedMap myMap;

Somewhere I found something similar for Maps:

 public class Test {
        private static final Map<Integer, String> MY_MAP = createMap();

        private static Map<Integer, String> createMap() {
            Map<Integer, String> result = new HashMap<Integer, String>();
            result.put(1, "one");
            result.put(2, "two");
            return Collections.unmodifiableMap(result);
        }
    }

But I can not apply the 'unmodifiableMap' method to LinkedMap. Can anybody help me? Is it possible at all?

+5
source share
2 answers

The most popular solution is almost Guava ImmutableMap . (Disclosure: I contribute to Guava.)

Map<Integer, String> map = ImmutableMap.of(
  1, "one",
  2, "two");

or

ImmutableMap<Integer, String> map = ImmutableMap
  .<Integer, String> builder()
  .put(1, "one")
  .put(2, "two")
  .build();

Without other libraries, the only workaround other than the one you wrote is

static final Map<Integer, String> CONSTANT_MAP;
static {
  Map<Integer, String> tmp = new LinkedHashMap<Integer, String>();
  tmp.put(1, "one");
  tmp.put(2, "two");
  CONSTANT_MAP = Collections.unmodifiableMap(tmp);
}
+10
source

It makes no sense to me to declare a variable that is equal to the Create () function.

myMap, :

// = createMap();
private final static LinkedHashMap<Integer, String> 
                                          myMap = new LinkedHashMap<Integer, String>();
static {
    myMap.put(1, "one");
    myMap.put(2, "Two");
};

public static void main(String[] args) {

  for( String link : myMap.values()){
    System.out.println("Value in myMap: "+link);
  }

}

create(), myMap myMap , :

    public static void main(String[] args) {

    myMap = Test.createMap();
0

All Articles