如何初始化一个公共静态最终只读LinkedMap(双向映射)

Jul*_*uly 5 java final map apache-commons-collection

我想创建一个

public static final LinkedMap myMap;
Run Code Online (Sandbox Code Playgroud)

在某个地方,我发现了类似地图的地图:

 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我不能将'unmodifiableMap'方法应用于它LinkedMap.有谁能够帮我?有可能吗?

Lou*_*man 10

最流行的解决方案几乎肯定是番石榴 ImmutableMap.(披露:我向番石榴捐款.)

Map<Integer, String> map = ImmutableMap.of(
  1, "one",
  2, "two");
Run Code Online (Sandbox Code Playgroud)

要么

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

没有其他库,除了你写的那个之外,唯一的解决方法是

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);
}
Run Code Online (Sandbox Code Playgroud)