10

I would like to create a

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 cannot apply the 'unmodifiableMap' method it to a LinkedMap. Can anybody help me? Is it possible at all?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Antje Janosch
  • 1,154
  • 5
  • 19
  • 37

2 Answers2

13

The most popular workaround is almost certainly a 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've written 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);
}
Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • does the ImmutableMap provide bidirectionality? – Antje Janosch May 16 '12 at 08:17
  • If you want bidirectionality -- and you mean [what I think you mean](http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#BiMap) by "bidirectionality" -- then [`ImmutableBiMap`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ImmutableBiMap.html) will do that. – Louis Wasserman May 16 '12 at 08:23
  • so, if I would neet the key of a certain value, I would have to retrieve the inverse of the map first, correct? – Antje Janosch May 16 '12 at 08:27
  • Yep, but that's an easy, constant-time operation: `map.inverse().get(value)`. – Louis Wasserman May 16 '12 at 08:34
0

It doesn't make any sense to me to declare variable which is equal to function Create().

If you need a final variable myMap you have to write like:

// = 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);
  }

}

or if you want to use create() function, you have to get rid of final keyword from myMap and use myMap in main like:

    public static void main(String[] args) {

    myMap = Test.createMap();
Rob Kielty
  • 7,958
  • 8
  • 39
  • 51
Hatto
  • 65
  • 2